From 2ffafb5f10c23c3c3082b266af4840b6245b8a92 Mon Sep 17 00:00:00 2001 From: Ruud Boon Date: Wed, 24 Jul 2019 22:52:00 +0300 Subject: [PATCH] Generated stubs for Phalcon v4.0.0-beta.1 --- src/Phalcon/Acl.php | 60 - src/Phalcon/Cache.php | 164 ++ src/Phalcon/Collection.php | 217 ++ src/Phalcon/Config.php | 180 +- src/Phalcon/Container.php | 55 +- src/Phalcon/Crypt.php | 306 ++- src/Phalcon/CryptInterface.php | 86 - src/Phalcon/Db.php | 108 - src/Phalcon/Debug.php | 191 +- src/Phalcon/Di.php | 363 ++- src/Phalcon/Escaper.php | 130 +- src/Phalcon/Exception.php | 8 +- src/Phalcon/Factory.php | 15 - src/Phalcon/FactoryInterface.php | 15 - src/Phalcon/Filter.php | 103 - src/Phalcon/FilterInterface.php | 38 - src/Phalcon/Flash.php | 181 -- src/Phalcon/FlashInterface.php | 49 - src/Phalcon/Image.php | 36 - src/Phalcon/Kernel.php | 4 +- src/Phalcon/Loader.php | 214 +- src/Phalcon/Logger.php | 55 - src/Phalcon/Plugin.php | 4 +- src/Phalcon/Registry.php | 184 +- src/Phalcon/Security.php | 202 +- src/Phalcon/Tag.php | 932 +++---- src/Phalcon/Text.php | 250 +- src/Phalcon/Translate.php | 14 - src/Phalcon/Url.php | 334 +-- src/Phalcon/Urlinterface.php | 44 - src/Phalcon/Validation.php | 153 +- src/Phalcon/Version.php | 50 +- src/Phalcon/acl/Component.php | 53 +- ...{Componentaware.php => ComponentAware.php} | 10 +- src/Phalcon/acl/ComponentInterface.php | 32 + src/Phalcon/acl/Componentinterface.php | 27 - src/Phalcon/acl/Enum.php | 17 + src/Phalcon/acl/Exception.php | 2 - src/Phalcon/acl/Role.php | 16 +- src/Phalcon/acl/RoleAware.php | 5 +- src/Phalcon/acl/RoleInterface.php | 8 +- .../AbstractAdapter.php} | 72 +- .../acl/{ => adapter}/AdapterInterface.php | 112 +- src/Phalcon/acl/adapter/Memory.php | 159 +- src/Phalcon/annotations/Annotation.php | 74 +- .../annotations/AnnotationsFactory.php | 42 + src/Phalcon/annotations/Collection.php | 87 +- src/Phalcon/annotations/Exception.php | 4 +- src/Phalcon/annotations/Factory.php | 28 - src/Phalcon/annotations/Reader.php | 8 +- src/Phalcon/annotations/ReaderInterface.php | 10 +- src/Phalcon/annotations/Reflection.php | 37 +- .../AbstractAdapter.php} | 64 +- .../{ => adapter}/AdapterInterface.php | 52 +- src/Phalcon/annotations/adapter/Apc.php | 51 - src/Phalcon/annotations/adapter/Apcu.php | 27 +- src/Phalcon/annotations/adapter/Memory.php | 15 +- .../adapter/{Files.php => Stream.php} | 26 +- src/Phalcon/annotations/adapter/Xcache.php | 33 - .../AbstractApplication.php} | 98 +- src/Phalcon/application/Exception.php | 2 - src/Phalcon/assets/Asset.php | 405 +-- src/Phalcon/assets/AssetInterface.php | 63 + src/Phalcon/assets/Assetinterface.php | 46 - src/Phalcon/assets/Collection.php | 376 +-- src/Phalcon/assets/Exception.php | 2 - src/Phalcon/assets/FilterInterface.php | 4 +- src/Phalcon/assets/Inline.php | 78 +- src/Phalcon/assets/Manager.php | 271 +- src/Phalcon/assets/Resource.php | 199 -- src/Phalcon/assets/ResourceInterface.php | 65 - src/Phalcon/assets/asset/Css.php | 25 +- src/Phalcon/assets/asset/Js.php | 25 +- src/Phalcon/assets/filters/Cssmin.php | 8 +- src/Phalcon/assets/filters/Jsmin.php | 11 +- src/Phalcon/assets/filters/None.php | 6 +- src/Phalcon/assets/inline/Css.php | 10 +- src/Phalcon/assets/inline/Js.php | 12 +- src/Phalcon/assets/resource/Css.php | 23 - src/Phalcon/assets/resource/Js.php | 23 - src/Phalcon/cache/AdapterFactory.php | 40 + src/Phalcon/cache/Backend.php | 103 - src/Phalcon/cache/BackendInterface.php | 116 - src/Phalcon/cache/CacheFactory.php | 40 + src/Phalcon/cache/Exception.php | 13 - src/Phalcon/cache/FrontendInterface.php | 58 - src/Phalcon/cache/Multiple.php | 139 -- .../cache/adapter/AdapterInterface.php | 11 + src/Phalcon/cache/adapter/Apcu.php | 11 + src/Phalcon/cache/adapter/Libmemcached.php | 11 + src/Phalcon/cache/adapter/Memory.php | 11 + src/Phalcon/cache/adapter/Redis.php | 11 + src/Phalcon/cache/adapter/Stream.php | 11 + src/Phalcon/cache/backend/Apc.php | 129 - src/Phalcon/cache/backend/Apcu.php | 126 - src/Phalcon/cache/backend/Factory.php | 35 - src/Phalcon/cache/backend/File.php | 152 -- src/Phalcon/cache/backend/Libmemcached.php | 162 -- src/Phalcon/cache/backend/Memcache.php | 148 -- src/Phalcon/cache/backend/Memory.php | 123 - src/Phalcon/cache/backend/Mongo.php | 146 -- src/Phalcon/cache/backend/Redis.php | 147 -- src/Phalcon/cache/backend/Xcache.php | 123 - src/Phalcon/cache/exception/Exception.php | 11 + .../exception/InvalidArgumentException.php | 11 + src/Phalcon/cache/frontend/Base64.php | 110 - src/Phalcon/cache/frontend/Data.php | 114 - src/Phalcon/cache/frontend/Factory.php | 33 - src/Phalcon/cache/frontend/Igbinary.php | 109 - src/Phalcon/cache/frontend/Json.php | 102 - src/Phalcon/cache/frontend/Msgpack.php | 115 - src/Phalcon/cache/frontend/None.php | 98 - src/Phalcon/cache/frontend/Output.php | 120 - src/Phalcon/cli/Console.php | 35 +- src/Phalcon/cli/Dispatcher.php | 133 +- src/Phalcon/cli/DispatcherInterface.php | 57 +- src/Phalcon/cli/Router.php | 195 +- src/Phalcon/cli/RouterInterface.php | 106 +- src/Phalcon/cli/Task.php | 16 +- src/Phalcon/cli/TaskInterface.php | 2 - src/Phalcon/cli/console/Exception.php | 2 - src/Phalcon/cli/dispatcher/Exception.php | 4 +- src/Phalcon/cli/router/Exception.php | 2 - src/Phalcon/cli/router/Route.php | 162 +- src/Phalcon/cli/router/RouteInterface.php | 75 +- src/Phalcon/collection/Exception.php | 11 + src/Phalcon/collection/ReadOnly.php | 26 + src/Phalcon/config/ConfigFactory.php | 55 + src/Phalcon/config/Exception.php | 2 - src/Phalcon/config/Factory.php | 33 - src/Phalcon/config/adapter/Grouped.php | 19 +- src/Phalcon/config/adapter/Ini.php | 56 +- src/Phalcon/config/adapter/Json.php | 16 +- src/Phalcon/config/adapter/Php.php | 16 +- src/Phalcon/config/adapter/Yaml.php | 17 +- src/Phalcon/crypt/CryptInterface.php | 137 + src/Phalcon/crypt/Exception.php | 2 - src/Phalcon/crypt/Mismatch.php | 2 - src/Phalcon/db/AbstractDb.php | 58 + src/Phalcon/db/Column.php | 317 +-- src/Phalcon/db/ColumnInterface.php | 97 +- src/Phalcon/db/Dialect.php | 254 +- src/Phalcon/db/DialectInterface.php | 242 +- src/Phalcon/db/Enum.php | 62 + src/Phalcon/db/Exception.php | 2 - src/Phalcon/db/Index.php | 50 +- src/Phalcon/db/IndexInterface.php | 22 +- src/Phalcon/db/Profiler.php | 62 +- src/Phalcon/db/RawValue.php | 12 +- src/Phalcon/db/Reference.php | 106 +- src/Phalcon/db/ReferenceInterface.php | 44 +- src/Phalcon/db/ResultInterface.php | 63 +- .../AbstractAdapter.php} | 958 +++---- .../db/{ => adapter}/AdapterInterface.php | 559 +++-- src/Phalcon/db/adapter/PdoFactory.php | 47 + .../adapter/{Pdo.php => pdo/AbstractPdo.php} | 341 +-- src/Phalcon/db/adapter/pdo/Factory.php | 31 - src/Phalcon/db/adapter/pdo/Mysql.php | 61 +- src/Phalcon/db/adapter/pdo/Postgresql.php | 113 +- src/Phalcon/db/adapter/pdo/Sqlite.php | 85 +- src/Phalcon/db/dialect/Mysql.php | 220 +- src/Phalcon/db/dialect/Postgresql.php | 208 +- src/Phalcon/db/dialect/Sqlite.php | 219 +- src/Phalcon/db/profiler/Item.php | 80 +- src/Phalcon/db/result/Pdo.php | 165 +- src/Phalcon/debug/Dump.php | 120 +- src/Phalcon/debug/Exception.php | 2 - src/Phalcon/{ => di}/DiInterface.php | 114 +- src/Phalcon/di/Exception.php | 2 - src/Phalcon/di/FactoryDefault.php | 7 +- src/Phalcon/di/Injectable.php | 53 +- src/Phalcon/di/InjectionAwareInterface.php | 14 +- src/Phalcon/di/Service.php | 99 +- src/Phalcon/di/ServiceInterface.php | 48 +- src/Phalcon/di/ServiceProviderInterface.php | 25 +- .../exception/ServiceResolutionException.php | 11 + .../exception/Serviceresolutionexception.php | 11 - src/Phalcon/di/service/Builder.php | 28 +- .../AbstractDispatcher.php} | 421 ++-- .../{ => dispatcher}/DispatcherInterface.php | 127 +- src/Phalcon/dispatcher/Exception.php | 29 + src/Phalcon/domain/payload/Payload.php | 121 + src/Phalcon/domain/payload/PayloadFactory.php | 18 + .../domain/payload/PayloadInterface.php | 11 + .../domain/payload/ReadableInterface.php | 47 + src/Phalcon/domain/payload/Status.php | 76 + .../domain/payload/WriteableInterface.php | 54 + .../{ => escaper}/EscaperInterface.php | 56 +- src/Phalcon/escaper/Exception.php | 2 - src/Phalcon/events/Event.php | 95 +- src/Phalcon/events/EventInterface.php | 38 +- src/Phalcon/events/EventsAwareInterface.php | 15 +- src/Phalcon/events/Manager.php | 116 +- src/Phalcon/events/ManagerInterface.php | 28 +- src/Phalcon/factory/AbstractFactory.php | 55 + src/Phalcon/factory/Exception.php | 7 +- src/Phalcon/filter/Filter.php | 154 ++ src/Phalcon/filter/FilterFactory.php | 29 + src/Phalcon/filter/FilterInterface.php | 21 + src/Phalcon/filter/Filterlocator.php | 51 - src/Phalcon/filter/Filterlocatorfactory.php | 42 - src/Phalcon/filter/UserFilterInterface.php | 20 - .../sanitize/{Absint.php => AbsInt.php} | 12 +- src/Phalcon/filter/sanitize/Alnum.php | 12 +- src/Phalcon/filter/sanitize/Alpha.php | 12 +- .../sanitize/{Boolval.php => BoolVal.php} | 12 +- src/Phalcon/filter/sanitize/Email.php | 12 +- .../sanitize/{Floatval.php => FloatVal.php} | 12 +- .../sanitize/{Intval.php => IntVal.php} | 12 +- src/Phalcon/filter/sanitize/Lower.php | 12 +- .../{Lowerfirst.php => LowerFirst.php} | 12 +- src/Phalcon/filter/sanitize/Regex.php | 14 +- src/Phalcon/filter/sanitize/Remove.php | 13 +- src/Phalcon/filter/sanitize/Replace.php | 14 +- src/Phalcon/filter/sanitize/Special.php | 12 +- .../{Specialfull.php => SpecialFull.php} | 12 +- .../sanitize/{Stringval.php => StringVal.php} | 12 +- src/Phalcon/filter/sanitize/Striptags.php | 12 +- src/Phalcon/filter/sanitize/Trim.php | 12 +- src/Phalcon/filter/sanitize/Upper.php | 12 +- .../{Upperfirst.php => UpperFirst.php} | 12 +- .../{Upperwords.php => UpperWords.php} | 12 +- src/Phalcon/filter/sanitize/Url.php | 12 +- src/Phalcon/firewall/Exception.php | 11 + .../firewall/adapter/AbstractAdapter.php | 190 ++ src/Phalcon/firewall/adapter/Acl.php | 174 ++ .../firewall/adapter/AdapterInterface.php | 61 + src/Phalcon/firewall/adapter/Annotations.php | 108 + src/Phalcon/firewall/adapter/micro/Acl.php | 197 ++ src/Phalcon/flash/AbstractFlash.php | 234 ++ src/Phalcon/flash/Direct.php | 11 +- src/Phalcon/flash/Exception.php | 2 - src/Phalcon/flash/FlashInterface.php | 53 + src/Phalcon/flash/Session.php | 53 +- src/Phalcon/forms/Exception.php | 2 - src/Phalcon/forms/Form.php | 258 +- src/Phalcon/forms/Manager.php | 12 +- .../AbstractElement.php} | 253 +- src/Phalcon/forms/element/Check.php | 4 +- src/Phalcon/forms/element/Date.php | 6 +- .../forms/{ => element}/ElementInterface.php | 224 +- src/Phalcon/forms/element/Email.php | 4 +- src/Phalcon/forms/element/File.php | 6 +- src/Phalcon/forms/element/Hidden.php | 4 +- src/Phalcon/forms/element/Numeric.php | 4 +- src/Phalcon/forms/element/Password.php | 4 +- src/Phalcon/forms/element/Radio.php | 4 +- src/Phalcon/forms/element/Select.php | 30 +- src/Phalcon/forms/element/Submit.php | 6 +- src/Phalcon/forms/element/Text.php | 4 +- src/Phalcon/forms/element/TextArea.php | 6 +- src/Phalcon/helper/Arr.php | 241 +- src/Phalcon/helper/Exception.php | 3 - src/Phalcon/helper/Number.php | 23 + src/Phalcon/helper/Str.php | 413 +++ src/Phalcon/html/Attributes.php | 25 + src/Phalcon/html/Breadcrumbs.php | 79 +- src/Phalcon/html/Exception.php | 1 - src/Phalcon/html/Tag.php | 2222 +++++++++-------- src/Phalcon/html/TagFactory.php | 38 + src/Phalcon/html/Taglocator.php | 14 - src/Phalcon/html/Taglocatorfactory.php | 42 - .../html/attributes/AttributesInterface.php | 28 + .../html/attributes/RenderInterface.php | 20 + src/Phalcon/html/helper/AbstractHelper.php | 73 + src/Phalcon/html/helper/Abstracthelper.php | 54 - src/Phalcon/html/helper/Anchor.php | 21 +- src/Phalcon/html/helper/AnchorRaw.php | 21 + src/Phalcon/html/helper/Body.php | 19 + src/Phalcon/html/helper/Button.php | 19 +- src/Phalcon/html/helper/Close.php | 21 + src/Phalcon/html/helper/Element.php | 21 +- src/Phalcon/html/helper/ElementRaw.php | 24 + src/Phalcon/html/helper/Form.php | 17 +- src/Phalcon/html/helper/Formclose.php | 20 - src/Phalcon/html/helper/Img.php | 23 + src/Phalcon/html/helper/Label.php | 22 + src/Phalcon/html/helper/TextArea.php | 20 + src/Phalcon/html/helper/Textarea.php | 21 - src/Phalcon/http/Cookie.php | 201 +- src/Phalcon/http/CookieInterface.php | 118 +- src/Phalcon/http/Request.php | 715 +++--- src/Phalcon/http/RequestInterface.php | 418 +++- src/Phalcon/http/Response.php | 382 +-- src/Phalcon/http/ResponseInterface.php | 122 +- src/Phalcon/http/message/AbstractCommon.php | 41 + src/Phalcon/http/message/AbstractMessage.php | 369 +++ src/Phalcon/http/message/AbstractRequest.php | 165 ++ src/Phalcon/http/message/Request.php | 21 + src/Phalcon/http/message/RequestFactory.php | 22 + src/Phalcon/http/message/Response.php | 123 + src/Phalcon/http/message/ResponseFactory.php | 25 + src/Phalcon/http/message/ServerRequest.php | 331 +++ .../http/message/ServerRequestFactory.php | 209 ++ src/Phalcon/http/message/Stream.php | 195 ++ src/Phalcon/http/message/StreamFactory.php | 52 + src/Phalcon/http/message/UploadedFile.php | 240 ++ .../http/message/UploadedFileFactory.php | 34 + src/Phalcon/http/message/Uri.php | 432 ++++ src/Phalcon/http/message/UriFactory.php | 20 + .../exception/InvalidArgumentException.php | 16 + src/Phalcon/http/message/stream/Input.php | 76 + src/Phalcon/http/message/stream/Memory.php | 22 + src/Phalcon/http/message/stream/Temp.php | 22 + src/Phalcon/http/request/File.php | 80 +- src/Phalcon/http/request/FileInterface.php | 28 +- src/Phalcon/http/response/Cookies.php | 129 +- .../http/response/CookiesInterface.php | 66 +- src/Phalcon/http/response/Headers.php | 46 +- .../http/response/HeadersInterface.php | 34 +- .../http/server/AbstractMiddleware.php | 28 + .../http/server/AbstractRequestHandler.php | 24 + src/Phalcon/image/AdapterInterface.php | 98 - src/Phalcon/image/Enum.php | 43 + src/Phalcon/image/Exception.php | 9 +- src/Phalcon/image/Factory.php | 35 - src/Phalcon/image/ImageFactory.php | 42 + .../AbstractAdapter.php} | 193 +- .../image/adapter/AdapterInterface.php | 105 + src/Phalcon/image/adapter/Gd.php | 130 +- src/Phalcon/image/adapter/Imagick.php | 183 +- src/Phalcon/logger/Adapter.php | 174 -- src/Phalcon/logger/AdapterFactory.php | 38 + src/Phalcon/logger/AdapterInterface.php | 144 -- src/Phalcon/logger/Factory.php | 33 - src/Phalcon/logger/Formatter.php | 30 - src/Phalcon/logger/FormatterInterface.php | 24 - src/Phalcon/logger/Item.php | 47 +- src/Phalcon/logger/Logger.php | 268 ++ src/Phalcon/logger/LoggerFactory.php | 42 + src/Phalcon/logger/Multiple.php | 125 - .../logger/adapter/AbstractAdapter.php | 105 + .../logger/adapter/Abstractadapter.php | 100 - .../logger/adapter/AdapterInterface.php | 70 + .../logger/adapter/Adapterinterface.php | 54 - src/Phalcon/logger/adapter/Blackhole.php | 37 - src/Phalcon/logger/adapter/File.php | 82 - src/Phalcon/logger/adapter/Firephp.php | 55 - src/Phalcon/logger/adapter/Noop.php | 34 +- src/Phalcon/logger/adapter/Stream.php | 71 +- src/Phalcon/logger/adapter/Syslog.php | 56 +- .../logger/formatter/AbstractFormatter.php | 25 + .../logger/formatter/Abstractformatter.php | 19 - src/Phalcon/logger/formatter/Firephp.php | 72 - ...erinterface.php => FormatterInterface.php} | 20 +- src/Phalcon/logger/formatter/Json.php | 37 +- src/Phalcon/logger/formatter/Line.php | 23 +- src/Phalcon/logger/formatter/Syslog.php | 9 +- src/Phalcon/messages/Exception.php | 3 +- src/Phalcon/messages/Message.php | 244 +- src/Phalcon/messages/MessageInterface.php | 95 + src/Phalcon/messages/Messageinterface.php | 72 - src/Phalcon/messages/Messages.php | 299 ++- src/Phalcon/mvc/Application.php | 43 +- src/Phalcon/mvc/Collection.php | 857 +++---- src/Phalcon/mvc/CollectionInterface.php | 143 +- src/Phalcon/mvc/Controller.php | 16 +- src/Phalcon/mvc/Dispatcher.php | 175 +- src/Phalcon/mvc/DispatcherInterface.php | 38 +- src/Phalcon/mvc/EntityInterface.php | 6 +- src/Phalcon/mvc/Micro.php | 308 +-- src/Phalcon/mvc/Model.php | 2067 ++++++++------- src/Phalcon/mvc/ModelInterface.php | 314 +-- src/Phalcon/mvc/ModuleDefinitionInterface.php | 8 +- src/Phalcon/mvc/Router.php | 467 ++-- src/Phalcon/mvc/RouterInterface.php | 188 +- src/Phalcon/mvc/Url.php | 184 -- src/Phalcon/mvc/View.php | 708 +++--- src/Phalcon/mvc/ViewBaseInterface.php | 69 +- src/Phalcon/mvc/ViewInterface.php | 176 +- src/Phalcon/mvc/collection/Behavior.php | 34 +- .../mvc/collection/BehaviorInterface.php | 14 +- src/Phalcon/mvc/collection/Document.php | 45 +- src/Phalcon/mvc/collection/Manager.php | 142 +- .../mvc/collection/ManagerInterface.php | 74 +- .../mvc/collection/behavior/SoftDelete.php | 2 +- .../mvc/collection/behavior/Timestampable.php | 2 +- .../mvc/controller/BindModelInterface.php | 2 +- src/Phalcon/mvc/dispatcher/Exception.php | 2 +- src/Phalcon/mvc/micro/Collection.php | 154 +- src/Phalcon/mvc/micro/CollectionInterface.php | 110 +- src/Phalcon/mvc/micro/Exception.php | 2 - src/Phalcon/mvc/micro/LazyLoader.php | 20 +- src/Phalcon/mvc/micro/MiddlewareInterface.php | 2 - src/Phalcon/mvc/model/Behavior.php | 38 +- src/Phalcon/mvc/model/BehaviorInterface.php | 14 +- src/Phalcon/mvc/model/Binder.php | 48 +- src/Phalcon/mvc/model/BinderInterface.php | 32 +- src/Phalcon/mvc/model/Criteria.php | 246 +- src/Phalcon/mvc/model/CriteriaInterface.php | 273 +- src/Phalcon/mvc/model/Manager.php | 374 ++- src/Phalcon/mvc/model/ManagerInterface.php | 426 ++-- src/Phalcon/mvc/model/Message.php | 147 -- src/Phalcon/mvc/model/MessageInterface.php | 70 - src/Phalcon/mvc/model/MetaData.php | 465 ++-- src/Phalcon/mvc/model/MetaDataInterface.php | 170 +- src/Phalcon/mvc/model/Query.php | 263 +- src/Phalcon/mvc/model/QueryInterface.php | 94 +- src/Phalcon/mvc/model/Relation.php | 124 +- src/Phalcon/mvc/model/RelationInterface.php | 89 +- src/Phalcon/mvc/model/ResultInterface.php | 5 +- src/Phalcon/mvc/model/Resultset.php | 227 +- src/Phalcon/mvc/model/ResultsetInterface.php | 88 +- src/Phalcon/mvc/model/Row.php | 54 +- src/Phalcon/mvc/model/Transaction.php | 102 +- .../mvc/model/TransactionInterface.php | 69 +- src/Phalcon/mvc/model/ValidationFailed.php | 20 +- src/Phalcon/mvc/model/Validator.php | 73 - src/Phalcon/mvc/model/ValidatorInterface.php | 31 - src/Phalcon/mvc/model/behavior/SoftDelete.php | 6 +- .../mvc/model/behavior/Timestampable.php | 11 +- .../mvc/model/binder/BindableInterface.php | 3 +- src/Phalcon/mvc/model/metadata/Apc.php | 61 - src/Phalcon/mvc/model/metadata/Apcu.php | 34 +- .../mvc/model/metadata/Libmemcached.php | 48 +- src/Phalcon/mvc/model/metadata/Memcache.php | 64 - src/Phalcon/mvc/model/metadata/Memory.php | 9 +- src/Phalcon/mvc/model/metadata/Redis.php | 35 +- src/Phalcon/mvc/model/metadata/Session.php | 50 - .../mvc/model/metadata/StrategyInterface.php | 23 +- .../model/metadata/{Files.php => Stream.php} | 26 +- src/Phalcon/mvc/model/metadata/Xcache.php | 58 - .../model/metadata/strategy/Annotations.php | 21 +- .../model/metadata/strategy/Introspection.php | 12 +- src/Phalcon/mvc/model/query/Builder.php | 835 ++++--- .../mvc/model/query/BuilderInterface.php | 319 ++- src/Phalcon/mvc/model/query/Lang.php | 10 +- src/Phalcon/mvc/model/query/Status.php | 26 +- .../mvc/model/query/StatusInterface.php | 14 +- src/Phalcon/mvc/model/resultset/Complex.php | 21 +- src/Phalcon/mvc/model/resultset/Simple.php | 36 +- src/Phalcon/mvc/model/transaction/Failed.php | 12 +- src/Phalcon/mvc/model/transaction/Manager.php | 133 +- .../model/transaction/ManagerInterface.php | 66 +- src/Phalcon/mvc/model/validator/Email.php | 49 - .../mvc/model/validator/Exclusionin.php | 50 - .../mvc/model/validator/Inclusionin.php | 50 - src/Phalcon/mvc/model/validator/Ip.php | 82 - .../mvc/model/validator/Numericality.php | 49 - .../mvc/model/validator/PresenceOf.php | 50 - src/Phalcon/mvc/model/validator/Regex.php | 50 - .../mvc/model/validator/StringLength.php | 53 - .../mvc/model/validator/Uniqueness.php | 52 - src/Phalcon/mvc/model/validator/Url.php | 49 - src/Phalcon/mvc/router/Annotations.php | 50 +- src/Phalcon/mvc/router/Group.php | 195 +- src/Phalcon/mvc/router/GroupInterface.php | 179 +- src/Phalcon/mvc/router/Route.php | 332 ++- src/Phalcon/mvc/router/RouteInterface.php | 93 +- src/Phalcon/mvc/url/Exception.php | 13 - src/Phalcon/mvc/user/Component.php | 14 - src/Phalcon/mvc/user/Module.php | 14 - src/Phalcon/mvc/user/Plugin.php | 14 - src/Phalcon/mvc/view/Simple.php | 255 +- .../{Engine.php => engine/AbstractEngine.php} | 30 +- .../mvc/view/{ => engine}/EngineInterface.php | 10 +- src/Phalcon/mvc/view/engine/Php.php | 6 +- src/Phalcon/mvc/view/engine/Volt.php | 80 +- src/Phalcon/mvc/view/engine/volt/Compiler.php | 433 ++-- .../mvc/view/engine/volt/Exception.php | 6 +- src/Phalcon/paginator/Adapter.php | 44 - src/Phalcon/paginator/Factory.php | 33 - src/Phalcon/paginator/PaginatorFactory.php | 65 + src/Phalcon/paginator/Repository.php | 217 +- src/Phalcon/paginator/RepositoryInterface.php | 117 + src/Phalcon/paginator/Repositoryinterface.php | 75 - .../paginator/adapter/AbstractAdapter.php | 79 + .../{ => adapter}/AdapterInterface.php | 25 +- src/Phalcon/paginator/adapter/Model.php | 35 +- src/Phalcon/paginator/adapter/NativeArray.php | 30 +- .../paginator/adapter/QueryBuilder.php | 41 +- src/Phalcon/queue/Beanstalk.php | 269 -- src/Phalcon/queue/beanstalk/Exception.php | 13 - src/Phalcon/queue/beanstalk/Job.php | 104 - src/Phalcon/security/Random.php | 167 +- src/Phalcon/service/Exception.php | 12 - src/Phalcon/service/Locator.php | 59 - .../service/Locatorfactoryinterface.php | 18 - src/Phalcon/service/Locatorinterface.php | 27 - src/Phalcon/session/Adapter.php | 251 -- src/Phalcon/session/AdapterInterface.php | 108 - src/Phalcon/session/Bag.php | 186 +- src/Phalcon/session/BagInterface.php | 73 - src/Phalcon/session/Factory.php | 32 - src/Phalcon/session/Manager.php | 445 ++-- src/Phalcon/session/ManagerInterface.php | 189 ++ src/Phalcon/session/Managerinterface.php | 139 -- .../session/adapter/AbstractAdapter.php | 70 + src/Phalcon/session/adapter/Files.php | 29 - src/Phalcon/session/adapter/Libmemcached.php | 92 +- src/Phalcon/session/adapter/Memcache.php | 95 - src/Phalcon/session/adapter/Noop.php | 152 +- src/Phalcon/session/adapter/Redis.php | 90 +- src/Phalcon/session/adapter/Stream.php | 70 + src/Phalcon/storage/AdapterFactory.php | 43 + src/Phalcon/storage/Exception.php | 13 + src/Phalcon/storage/SerializerFactory.php | 37 + .../storage/adapter/AbstractAdapter.php | 195 ++ .../storage/adapter/AdapterInterface.php | 92 + src/Phalcon/storage/adapter/Apcu.php | 112 + src/Phalcon/storage/adapter/Libmemcached.php | 125 + src/Phalcon/storage/adapter/Memory.php | 116 + src/Phalcon/storage/adapter/Redis.php | 128 + src/Phalcon/storage/adapter/Stream.php | 156 ++ .../storage/serializer/AbstractSerializer.php | 46 + src/Phalcon/storage/serializer/Base64.php | 30 + src/Phalcon/storage/serializer/Igbinary.php | 30 + src/Phalcon/storage/serializer/Json.php | 30 + src/Phalcon/storage/serializer/Msgpack.php | 30 + src/Phalcon/storage/serializer/None.php | 30 + src/Phalcon/storage/serializer/Php.php | 30 + .../serializer/SerializerInterface.php | 27 + src/Phalcon/tag/Select.php | 22 +- src/Phalcon/translate/Factory.php | 30 - src/Phalcon/translate/InterpolatorFactory.php | 46 + .../translate/InterpolatorInterface.php | 22 - src/Phalcon/translate/TranslateFactory.php | 51 + .../AbstractAdapter.php} | 58 +- .../{ => adapter}/AdapterInterface.php | 32 +- src/Phalcon/translate/adapter/Csv.php | 33 +- src/Phalcon/translate/adapter/Gettext.php | 102 +- src/Phalcon/translate/adapter/NativeArray.php | 34 +- .../interpolator/AssociativeArray.php | 15 +- .../translate/interpolator/IndexedArray.php | 15 +- .../interpolator/InterpolatorInterface.php | 22 + src/Phalcon/{mvc => url}/UrlInterface.php | 45 +- .../AbstractCombinedFieldsValidator.php | 11 + src/Phalcon/validation/AbstractValidator.php | 132 + .../validation/AbstractValidatorComposite.php | 30 + .../validation/CombinedFieldsValidator.php | 13 - src/Phalcon/validation/Exception.php | 2 - src/Phalcon/validation/Message.php | 110 - src/Phalcon/validation/MessageInterface.php | 73 - .../{ => validation}/ValidationInterface.php | 121 +- src/Phalcon/validation/Validator.php | 97 - .../ValidatorCompositeInterface.php | 27 + src/Phalcon/validation/ValidatorFactory.php | 36 + src/Phalcon/validation/ValidatorInterface.php | 56 +- src/Phalcon/validation/message/Group.php | 155 -- src/Phalcon/validation/validator/Alnum.php | 15 +- src/Phalcon/validation/validator/Alpha.php | 15 +- src/Phalcon/validation/validator/Between.php | 15 +- src/Phalcon/validation/validator/Callback.php | 15 +- .../validation/validator/Confirmation.php | 17 +- .../validation/validator/CreditCard.php | 20 +- src/Phalcon/validation/validator/Date.php | 17 +- src/Phalcon/validation/validator/Digit.php | 15 +- src/Phalcon/validation/validator/Email.php | 15 +- .../validation/validator/Exception.php | 5 +- .../validation/validator/ExclusionIn.php | 15 +- src/Phalcon/validation/validator/File.php | 29 +- .../validation/validator/Identical.php | 15 +- .../validation/validator/InclusionIn.php | 15 +- src/Phalcon/validation/validator/Ip.php | 60 +- .../validation/validator/Numericality.php | 15 +- .../validation/validator/PresenceOf.php | 15 +- src/Phalcon/validation/validator/Regex.php | 15 +- .../validation/validator/StringLength.php | 35 +- .../validation/validator/Uniqueness.php | 53 +- src/Phalcon/validation/validator/Url.php | 15 +- .../validator/file/AbstractFile.php | 151 ++ .../validation/validator/file/MimeType.php | 68 + .../validator/file/resolution/Equal.php | 59 + .../validator/file/resolution/Max.php | 64 + .../validator/file/resolution/Min.php | 64 + .../validation/validator/file/size/Equal.php | 64 + .../validation/validator/file/size/Max.php | 64 + .../validation/validator/file/size/Min.php | 64 + .../validation/validator/stringlength/Max.php | 66 + .../validation/validator/stringlength/Min.php | 66 + 570 files changed, 28064 insertions(+), 25274 deletions(-) delete mode 100644 src/Phalcon/Acl.php create mode 100644 src/Phalcon/Cache.php create mode 100644 src/Phalcon/Collection.php delete mode 100644 src/Phalcon/CryptInterface.php delete mode 100644 src/Phalcon/Db.php delete mode 100644 src/Phalcon/Factory.php delete mode 100644 src/Phalcon/FactoryInterface.php delete mode 100644 src/Phalcon/Filter.php delete mode 100644 src/Phalcon/FilterInterface.php delete mode 100644 src/Phalcon/Flash.php delete mode 100644 src/Phalcon/FlashInterface.php delete mode 100644 src/Phalcon/Image.php delete mode 100644 src/Phalcon/Logger.php delete mode 100644 src/Phalcon/Translate.php delete mode 100644 src/Phalcon/Urlinterface.php rename src/Phalcon/acl/{Componentaware.php => ComponentAware.php} (66%) create mode 100644 src/Phalcon/acl/ComponentInterface.php delete mode 100644 src/Phalcon/acl/Componentinterface.php create mode 100644 src/Phalcon/acl/Enum.php rename src/Phalcon/acl/{Adapter.php => adapter/AbstractAdapter.php} (58%) rename src/Phalcon/acl/{ => adapter}/AdapterInterface.php (57%) create mode 100644 src/Phalcon/annotations/AnnotationsFactory.php delete mode 100644 src/Phalcon/annotations/Factory.php rename src/Phalcon/annotations/{Adapter.php => adapter/AbstractAdapter.php} (63%) rename src/Phalcon/annotations/{ => adapter}/AdapterInterface.php (72%) delete mode 100644 src/Phalcon/annotations/adapter/Apc.php rename src/Phalcon/annotations/adapter/{Files.php => Stream.php} (55%) delete mode 100644 src/Phalcon/annotations/adapter/Xcache.php rename src/Phalcon/{Application.php => application/AbstractApplication.php} (58%) create mode 100644 src/Phalcon/assets/AssetInterface.php delete mode 100644 src/Phalcon/assets/Assetinterface.php delete mode 100644 src/Phalcon/assets/Resource.php delete mode 100644 src/Phalcon/assets/ResourceInterface.php delete mode 100644 src/Phalcon/assets/resource/Css.php delete mode 100644 src/Phalcon/assets/resource/Js.php create mode 100644 src/Phalcon/cache/AdapterFactory.php delete mode 100644 src/Phalcon/cache/Backend.php delete mode 100644 src/Phalcon/cache/BackendInterface.php create mode 100644 src/Phalcon/cache/CacheFactory.php delete mode 100644 src/Phalcon/cache/Exception.php delete mode 100644 src/Phalcon/cache/FrontendInterface.php delete mode 100644 src/Phalcon/cache/Multiple.php create mode 100644 src/Phalcon/cache/adapter/AdapterInterface.php create mode 100644 src/Phalcon/cache/adapter/Apcu.php create mode 100644 src/Phalcon/cache/adapter/Libmemcached.php create mode 100644 src/Phalcon/cache/adapter/Memory.php create mode 100644 src/Phalcon/cache/adapter/Redis.php create mode 100644 src/Phalcon/cache/adapter/Stream.php delete mode 100644 src/Phalcon/cache/backend/Apc.php delete mode 100644 src/Phalcon/cache/backend/Apcu.php delete mode 100644 src/Phalcon/cache/backend/Factory.php delete mode 100644 src/Phalcon/cache/backend/File.php delete mode 100644 src/Phalcon/cache/backend/Libmemcached.php delete mode 100644 src/Phalcon/cache/backend/Memcache.php delete mode 100644 src/Phalcon/cache/backend/Memory.php delete mode 100644 src/Phalcon/cache/backend/Mongo.php delete mode 100644 src/Phalcon/cache/backend/Redis.php delete mode 100644 src/Phalcon/cache/backend/Xcache.php create mode 100644 src/Phalcon/cache/exception/Exception.php create mode 100644 src/Phalcon/cache/exception/InvalidArgumentException.php delete mode 100644 src/Phalcon/cache/frontend/Base64.php delete mode 100644 src/Phalcon/cache/frontend/Data.php delete mode 100644 src/Phalcon/cache/frontend/Factory.php delete mode 100644 src/Phalcon/cache/frontend/Igbinary.php delete mode 100644 src/Phalcon/cache/frontend/Json.php delete mode 100644 src/Phalcon/cache/frontend/Msgpack.php delete mode 100644 src/Phalcon/cache/frontend/None.php delete mode 100644 src/Phalcon/cache/frontend/Output.php create mode 100644 src/Phalcon/collection/Exception.php create mode 100644 src/Phalcon/collection/ReadOnly.php create mode 100644 src/Phalcon/config/ConfigFactory.php delete mode 100644 src/Phalcon/config/Factory.php create mode 100644 src/Phalcon/crypt/CryptInterface.php create mode 100644 src/Phalcon/db/AbstractDb.php create mode 100644 src/Phalcon/db/Enum.php rename src/Phalcon/db/{Adapter.php => adapter/AbstractAdapter.php} (68%) rename src/Phalcon/db/{ => adapter}/AdapterInterface.php (52%) create mode 100644 src/Phalcon/db/adapter/PdoFactory.php rename src/Phalcon/db/adapter/{Pdo.php => pdo/AbstractPdo.php} (75%) delete mode 100644 src/Phalcon/db/adapter/pdo/Factory.php rename src/Phalcon/{ => di}/DiInterface.php (63%) create mode 100644 src/Phalcon/di/exception/ServiceResolutionException.php delete mode 100644 src/Phalcon/di/exception/Serviceresolutionexception.php rename src/Phalcon/{Dispatcher.php => dispatcher/AbstractDispatcher.php} (54%) rename src/Phalcon/{ => dispatcher}/DispatcherInterface.php (63%) create mode 100644 src/Phalcon/dispatcher/Exception.php create mode 100644 src/Phalcon/domain/payload/Payload.php create mode 100644 src/Phalcon/domain/payload/PayloadFactory.php create mode 100644 src/Phalcon/domain/payload/PayloadInterface.php create mode 100644 src/Phalcon/domain/payload/ReadableInterface.php create mode 100644 src/Phalcon/domain/payload/Status.php create mode 100644 src/Phalcon/domain/payload/WriteableInterface.php rename src/Phalcon/{ => escaper}/EscaperInterface.php (65%) create mode 100644 src/Phalcon/factory/AbstractFactory.php create mode 100644 src/Phalcon/filter/Filter.php create mode 100644 src/Phalcon/filter/FilterFactory.php create mode 100644 src/Phalcon/filter/FilterInterface.php delete mode 100644 src/Phalcon/filter/Filterlocator.php delete mode 100644 src/Phalcon/filter/Filterlocatorfactory.php delete mode 100644 src/Phalcon/filter/UserFilterInterface.php rename src/Phalcon/filter/sanitize/{Absint.php => AbsInt.php} (61%) rename src/Phalcon/filter/sanitize/{Boolval.php => BoolVal.php} (60%) rename src/Phalcon/filter/sanitize/{Floatval.php => FloatVal.php} (60%) rename src/Phalcon/filter/sanitize/{Intval.php => IntVal.php} (59%) rename src/Phalcon/filter/sanitize/{Lowerfirst.php => LowerFirst.php} (59%) rename src/Phalcon/filter/sanitize/{Specialfull.php => SpecialFull.php} (67%) rename src/Phalcon/filter/sanitize/{Stringval.php => StringVal.php} (60%) rename src/Phalcon/filter/sanitize/{Upperfirst.php => UpperFirst.php} (59%) rename src/Phalcon/filter/sanitize/{Upperwords.php => UpperWords.php} (64%) create mode 100644 src/Phalcon/firewall/Exception.php create mode 100644 src/Phalcon/firewall/adapter/AbstractAdapter.php create mode 100644 src/Phalcon/firewall/adapter/Acl.php create mode 100644 src/Phalcon/firewall/adapter/AdapterInterface.php create mode 100644 src/Phalcon/firewall/adapter/Annotations.php create mode 100644 src/Phalcon/firewall/adapter/micro/Acl.php create mode 100644 src/Phalcon/flash/AbstractFlash.php create mode 100644 src/Phalcon/flash/FlashInterface.php rename src/Phalcon/forms/{Element.php => element/AbstractElement.php} (58%) rename src/Phalcon/forms/{ => element}/ElementInterface.php (67%) create mode 100644 src/Phalcon/helper/Number.php create mode 100644 src/Phalcon/helper/Str.php create mode 100644 src/Phalcon/html/Attributes.php create mode 100644 src/Phalcon/html/TagFactory.php delete mode 100644 src/Phalcon/html/Taglocator.php delete mode 100644 src/Phalcon/html/Taglocatorfactory.php create mode 100644 src/Phalcon/html/attributes/AttributesInterface.php create mode 100644 src/Phalcon/html/attributes/RenderInterface.php create mode 100644 src/Phalcon/html/helper/AbstractHelper.php delete mode 100644 src/Phalcon/html/helper/Abstracthelper.php create mode 100644 src/Phalcon/html/helper/AnchorRaw.php create mode 100644 src/Phalcon/html/helper/Body.php create mode 100644 src/Phalcon/html/helper/Close.php create mode 100644 src/Phalcon/html/helper/ElementRaw.php delete mode 100644 src/Phalcon/html/helper/Formclose.php create mode 100644 src/Phalcon/html/helper/Img.php create mode 100644 src/Phalcon/html/helper/Label.php create mode 100644 src/Phalcon/html/helper/TextArea.php delete mode 100644 src/Phalcon/html/helper/Textarea.php create mode 100644 src/Phalcon/http/message/AbstractCommon.php create mode 100644 src/Phalcon/http/message/AbstractMessage.php create mode 100644 src/Phalcon/http/message/AbstractRequest.php create mode 100644 src/Phalcon/http/message/Request.php create mode 100644 src/Phalcon/http/message/RequestFactory.php create mode 100644 src/Phalcon/http/message/Response.php create mode 100644 src/Phalcon/http/message/ResponseFactory.php create mode 100644 src/Phalcon/http/message/ServerRequest.php create mode 100644 src/Phalcon/http/message/ServerRequestFactory.php create mode 100644 src/Phalcon/http/message/Stream.php create mode 100644 src/Phalcon/http/message/StreamFactory.php create mode 100644 src/Phalcon/http/message/UploadedFile.php create mode 100644 src/Phalcon/http/message/UploadedFileFactory.php create mode 100644 src/Phalcon/http/message/Uri.php create mode 100644 src/Phalcon/http/message/UriFactory.php create mode 100644 src/Phalcon/http/message/exception/InvalidArgumentException.php create mode 100644 src/Phalcon/http/message/stream/Input.php create mode 100644 src/Phalcon/http/message/stream/Memory.php create mode 100644 src/Phalcon/http/message/stream/Temp.php create mode 100644 src/Phalcon/http/server/AbstractMiddleware.php create mode 100644 src/Phalcon/http/server/AbstractRequestHandler.php delete mode 100644 src/Phalcon/image/AdapterInterface.php create mode 100644 src/Phalcon/image/Enum.php delete mode 100644 src/Phalcon/image/Factory.php create mode 100644 src/Phalcon/image/ImageFactory.php rename src/Phalcon/image/{Adapter.php => adapter/AbstractAdapter.php} (63%) create mode 100644 src/Phalcon/image/adapter/AdapterInterface.php delete mode 100644 src/Phalcon/logger/Adapter.php create mode 100644 src/Phalcon/logger/AdapterFactory.php delete mode 100644 src/Phalcon/logger/AdapterInterface.php delete mode 100644 src/Phalcon/logger/Factory.php delete mode 100644 src/Phalcon/logger/Formatter.php delete mode 100644 src/Phalcon/logger/FormatterInterface.php create mode 100644 src/Phalcon/logger/Logger.php create mode 100644 src/Phalcon/logger/LoggerFactory.php delete mode 100644 src/Phalcon/logger/Multiple.php create mode 100644 src/Phalcon/logger/adapter/AbstractAdapter.php delete mode 100644 src/Phalcon/logger/adapter/Abstractadapter.php create mode 100644 src/Phalcon/logger/adapter/AdapterInterface.php delete mode 100644 src/Phalcon/logger/adapter/Adapterinterface.php delete mode 100644 src/Phalcon/logger/adapter/Blackhole.php delete mode 100644 src/Phalcon/logger/adapter/File.php delete mode 100644 src/Phalcon/logger/adapter/Firephp.php create mode 100644 src/Phalcon/logger/formatter/AbstractFormatter.php delete mode 100644 src/Phalcon/logger/formatter/Abstractformatter.php delete mode 100644 src/Phalcon/logger/formatter/Firephp.php rename src/Phalcon/logger/formatter/{Formatterinterface.php => FormatterInterface.php} (51%) create mode 100644 src/Phalcon/messages/MessageInterface.php delete mode 100644 src/Phalcon/messages/Messageinterface.php delete mode 100644 src/Phalcon/mvc/Url.php delete mode 100644 src/Phalcon/mvc/model/Message.php delete mode 100644 src/Phalcon/mvc/model/MessageInterface.php delete mode 100644 src/Phalcon/mvc/model/Validator.php delete mode 100644 src/Phalcon/mvc/model/ValidatorInterface.php delete mode 100644 src/Phalcon/mvc/model/metadata/Apc.php delete mode 100644 src/Phalcon/mvc/model/metadata/Memcache.php delete mode 100644 src/Phalcon/mvc/model/metadata/Session.php rename src/Phalcon/mvc/model/metadata/{Files.php => Stream.php} (57%) delete mode 100644 src/Phalcon/mvc/model/metadata/Xcache.php delete mode 100644 src/Phalcon/mvc/model/validator/Email.php delete mode 100644 src/Phalcon/mvc/model/validator/Exclusionin.php delete mode 100644 src/Phalcon/mvc/model/validator/Inclusionin.php delete mode 100644 src/Phalcon/mvc/model/validator/Ip.php delete mode 100644 src/Phalcon/mvc/model/validator/Numericality.php delete mode 100644 src/Phalcon/mvc/model/validator/PresenceOf.php delete mode 100644 src/Phalcon/mvc/model/validator/Regex.php delete mode 100644 src/Phalcon/mvc/model/validator/StringLength.php delete mode 100644 src/Phalcon/mvc/model/validator/Uniqueness.php delete mode 100644 src/Phalcon/mvc/model/validator/Url.php delete mode 100644 src/Phalcon/mvc/url/Exception.php delete mode 100644 src/Phalcon/mvc/user/Component.php delete mode 100644 src/Phalcon/mvc/user/Module.php delete mode 100644 src/Phalcon/mvc/user/Plugin.php rename src/Phalcon/mvc/view/{Engine.php => engine/AbstractEngine.php} (62%) rename src/Phalcon/mvc/view/{ => engine}/EngineInterface.php (68%) delete mode 100644 src/Phalcon/paginator/Adapter.php delete mode 100644 src/Phalcon/paginator/Factory.php create mode 100644 src/Phalcon/paginator/PaginatorFactory.php create mode 100644 src/Phalcon/paginator/RepositoryInterface.php delete mode 100644 src/Phalcon/paginator/Repositoryinterface.php create mode 100644 src/Phalcon/paginator/adapter/AbstractAdapter.php rename src/Phalcon/paginator/{ => adapter}/AdapterInterface.php (62%) delete mode 100644 src/Phalcon/queue/Beanstalk.php delete mode 100644 src/Phalcon/queue/beanstalk/Exception.php delete mode 100644 src/Phalcon/queue/beanstalk/Job.php delete mode 100644 src/Phalcon/service/Exception.php delete mode 100644 src/Phalcon/service/Locator.php delete mode 100644 src/Phalcon/service/Locatorfactoryinterface.php delete mode 100644 src/Phalcon/service/Locatorinterface.php delete mode 100644 src/Phalcon/session/Adapter.php delete mode 100644 src/Phalcon/session/AdapterInterface.php delete mode 100644 src/Phalcon/session/BagInterface.php delete mode 100644 src/Phalcon/session/Factory.php create mode 100644 src/Phalcon/session/ManagerInterface.php delete mode 100644 src/Phalcon/session/Managerinterface.php create mode 100644 src/Phalcon/session/adapter/AbstractAdapter.php delete mode 100644 src/Phalcon/session/adapter/Files.php delete mode 100644 src/Phalcon/session/adapter/Memcache.php create mode 100644 src/Phalcon/session/adapter/Stream.php create mode 100644 src/Phalcon/storage/AdapterFactory.php create mode 100644 src/Phalcon/storage/Exception.php create mode 100644 src/Phalcon/storage/SerializerFactory.php create mode 100644 src/Phalcon/storage/adapter/AbstractAdapter.php create mode 100644 src/Phalcon/storage/adapter/AdapterInterface.php create mode 100644 src/Phalcon/storage/adapter/Apcu.php create mode 100644 src/Phalcon/storage/adapter/Libmemcached.php create mode 100644 src/Phalcon/storage/adapter/Memory.php create mode 100644 src/Phalcon/storage/adapter/Redis.php create mode 100644 src/Phalcon/storage/adapter/Stream.php create mode 100644 src/Phalcon/storage/serializer/AbstractSerializer.php create mode 100644 src/Phalcon/storage/serializer/Base64.php create mode 100644 src/Phalcon/storage/serializer/Igbinary.php create mode 100644 src/Phalcon/storage/serializer/Json.php create mode 100644 src/Phalcon/storage/serializer/Msgpack.php create mode 100644 src/Phalcon/storage/serializer/None.php create mode 100644 src/Phalcon/storage/serializer/Php.php create mode 100644 src/Phalcon/storage/serializer/SerializerInterface.php delete mode 100644 src/Phalcon/translate/Factory.php create mode 100644 src/Phalcon/translate/InterpolatorFactory.php delete mode 100644 src/Phalcon/translate/InterpolatorInterface.php create mode 100644 src/Phalcon/translate/TranslateFactory.php rename src/Phalcon/translate/{Adapter.php => adapter/AbstractAdapter.php} (58%) rename src/Phalcon/translate/{ => adapter}/AdapterInterface.php (53%) create mode 100644 src/Phalcon/translate/interpolator/InterpolatorInterface.php rename src/Phalcon/{mvc => url}/UrlInterface.php (61%) create mode 100644 src/Phalcon/validation/AbstractCombinedFieldsValidator.php create mode 100644 src/Phalcon/validation/AbstractValidator.php create mode 100644 src/Phalcon/validation/AbstractValidatorComposite.php delete mode 100644 src/Phalcon/validation/CombinedFieldsValidator.php delete mode 100644 src/Phalcon/validation/Message.php delete mode 100644 src/Phalcon/validation/MessageInterface.php rename src/Phalcon/{ => validation}/ValidationInterface.php (56%) delete mode 100644 src/Phalcon/validation/Validator.php create mode 100644 src/Phalcon/validation/ValidatorCompositeInterface.php create mode 100644 src/Phalcon/validation/ValidatorFactory.php delete mode 100644 src/Phalcon/validation/message/Group.php create mode 100644 src/Phalcon/validation/validator/file/AbstractFile.php create mode 100644 src/Phalcon/validation/validator/file/MimeType.php create mode 100644 src/Phalcon/validation/validator/file/resolution/Equal.php create mode 100644 src/Phalcon/validation/validator/file/resolution/Max.php create mode 100644 src/Phalcon/validation/validator/file/resolution/Min.php create mode 100644 src/Phalcon/validation/validator/file/size/Equal.php create mode 100644 src/Phalcon/validation/validator/file/size/Max.php create mode 100644 src/Phalcon/validation/validator/file/size/Min.php create mode 100644 src/Phalcon/validation/validator/stringlength/Max.php create mode 100644 src/Phalcon/validation/validator/stringlength/Min.php diff --git a/src/Phalcon/Acl.php b/src/Phalcon/Acl.php deleted file mode 100644 index 498be5ea..00000000 --- a/src/Phalcon/Acl.php +++ /dev/null @@ -1,60 +0,0 @@ - - * use Phalcon\Acl; - * use Phalcon\Acl\Role; - * use Phalcon\Acl\Resource; - * use Phalcon\Acl\Adapter\Memory; - * - * $acl = new Memory(); - * - * // Default action is deny access - * $acl->setDefaultAction(Acl::DENY); - * - * // Create some roles - * $roleAdmins = new Role("Administrators", "Super-User role"); - * $roleGuests = new Role("Guests"); - * - * // Add "Guests" role to acl - * $acl->addRole($roleGuests); - * - * // Add "Designers" role to acl - * $acl->addRole("Designers"); - * - * // Define the "Customers" resource - * $customersResource = new Resource("Customers", "Customers management"); - * - * // Add "customers" resource with a couple of operations - * $acl->addResource($customersResource, "search"); - * $acl->addResource($customersResource, ["create", "update"]); - * - * // Set access level for roles into resources - * $acl->allow("Guests", "Customers", "search"); - * $acl->allow("Guests", "Customers", "create"); - * $acl->deny("Guests", "Customers", "update"); - * - * // Check whether role has access to the operations - * $acl->isAllowed("Guests", "Customers", "edit"); // Returns 0 - * $acl->isAllowed("Guests", "Customers", "search"); // Returns 1 - * $acl->isAllowed("Guests", "Customers", "create"); // Returns 1 - * - */ -abstract class Acl -{ - - const ALLOW = 1; - - - const DENY = 0; - - -} diff --git a/src/Phalcon/Cache.php b/src/Phalcon/Cache.php new file mode 100644 index 00000000..444fa3d7 --- /dev/null +++ b/src/Phalcon/Cache.php @@ -0,0 +1,164 @@ + value pairs. Cache keys that do not exist or are stale will have $default as value. + * + * @throws Phalcon\Cache\Exception\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + * @param iterable $keys A list of keys that can obtained in a single operation. + * @param mixed $defaultValue + * @return mixed + */ + public function getMultiple($keys, $defaultValue = null) {} + + /** + * Determines whether an item is present in the cache. + * + * @param string $key The cache item key. + * + * @return bool + * + * @throws Phalcon\Cache\Exception\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + * @param mixed $key + * @return bool + */ + public function has($key): bool {} + + /** + * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. + * + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * + * @return bool True on success and false on failure. + * + * @throws Phalcon\Cache\Exception\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + * @param string $key The key of the item to store. + * @param mixed $value The value of the item to store. Must be serializable. + * @param mixed $ttl + * @return bool + */ + public function set($key, $value, $ttl = null): bool {} + + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * + * @return bool True on success and false on failure. + * + * @throws Phalcon\Cache\Exception\InvalidArgumentException + * MUST be thrown if $values is neither an array nor a Traversable, + * or if any of the $values are not a legal value. + * @param iterable $values A list of key => value pairs for a multiple-set operation. + * @param mixed $ttl + * @return bool + */ + public function setMultiple($values, $ttl = null): bool {} + + /** + * Checks the key. If it contains invalid characters an exception is thrown + * + * @param mixed $key + */ + protected function checkKey($key) {} + + /** + * Checks the key. If it contains invalid characters an exception is thrown + * + * @param mixed $keys + */ + protected function checkKeys($keys) {} + +} diff --git a/src/Phalcon/Collection.php b/src/Phalcon/Collection.php new file mode 100644 index 00000000..ecde5727 --- /dev/null +++ b/src/Phalcon/Collection.php @@ -0,0 +1,217 @@ + + * ```php * $config = new \Phalcon\Config( * [ * "database" => [ @@ -26,109 +25,30 @@ * ], * ] * ); - * + * ``` */ -class Config implements \ArrayAccess, \Countable +class Config extends \Phalcon\Collection { const DEFAULT_PATH_DELIMITER = '.'; - - static protected $_pathDelimiter; - - /** - * Phalcon\Config constructor - * - * @param array $arrayConfig + * @var string */ - public function __construct(array $arrayConfig = null) {} + protected $pathDelimiter = null; - /** - * Allows to check whether an attribute is defined using the array-syntax - * - * - * var_dump( - * isset($config["database"]) - * ); - * - * - * @param mixed $index - * @return bool - */ - public function offsetExists($index) {} /** - * Returns a value from current config using a dot separated path. - * - * - * echo $config->path("unknown.path", "default", "."); - * - * - * @param string $path - * @param mixed $defaultValue - * @param mixed $delimiter - * @return mixed - */ - public function path($path, $defaultValue = null, $delimiter = null) {} - - /** - * Gets an attribute from the configuration, if the attribute isn't defined returns null - * If the value is exactly null or is not defined the default value will be used instead - * - * - * echo $config->get("controllersDir", "../app/controllers/"); - * - * - * @param mixed $index - * @param mixed $defaultValue - * @return mixed - */ - public function get($index, $defaultValue = null) {} - - /** - * Gets an attribute using the array-syntax - * - * - * print_r( - * $config["database"] - * ); - * + * Gets the default path delimiter * - * @param mixed $index * @return string */ - public function offsetGet($index) {} - - /** - * Sets an attribute using the array-syntax - * - * - * $config["database"] = [ - * "type" => "Sqlite", - * ]; - * - * - * @param mixed $index - * @param mixed $value - */ - public function offsetSet($index, $value) {} - - /** - * Unsets an attribute using the array-syntax - * - * - * unset($config["database"]); - * - * - * @param mixed $index - */ - public function offsetUnset($index) {} + public function getPathDelimiter(): string {} /** * Merges a configuration into the current one * - * + * ```php * $appConfig = new \Phalcon\Config( * [ * "database" => [ @@ -138,74 +58,62 @@ public function offsetUnset($index) {} * ); * * $globalConfig->merge($appConfig); - * + * ``` * - * @param Config $config + * @param mixed $toMerge * @return Config */ - public function merge(Config $config) {} + public function merge($toMerge): Config {} /** - * Converts recursively the object to an array - * - * - * print_r( - * $config->toArray() - * ); - * - * - * @return array - */ - public function toArray() {} - - /** - * Returns the count of properties set in the config - * - * - * print count($config); - * - * - * or + * Returns a value from current config using a dot separated path. * - * - * print $config->count(); - * + * ```php + * echo $config->path("unknown.path", "default", "."); + * ``` * - * @return int + * @param string $path + * @param mixed $defaultValue + * @param mixed $delimiter */ - public function count() {} + public function path(string $path, $defaultValue = null, $delimiter = null) {} /** - * Restores the state of a Phalcon\Config object + * Sets the default path delimiter * - * @param array $data + * @param string $delimiter * @return Config */ - public static function __set_state(array $data) {} + public function setPathDelimiter(string $delimiter = null): Config {} /** - * Sets the default path delimiter + * Converts recursively the object to an array * - * @param string $delimiter + * ```php + * print_r( + * $config->toArray() + * ); + * ``` + * + * @return array */ - public static function setPathDelimiter($delimiter = null) {} + public function toArray(): array {} /** - * Gets the default path delimiter + * Performs a merge recursively * - * @return string + * @param array $source + * @param array $target + * @return array */ - public static function getPathDelimiter() {} + final protected function internalMerge(array $source, array $target): array {} /** - * Helper method for merge configs (forwarding nested config instance) - * - * @param Config instance = null + * Sets the collection data * - * @param Config $config - * @param mixed $instance - * @return Config + * @param mixed $element + * @param mixed $value */ - protected final function _merge(Config $config, $instance = null) {} + protected function setData($element, $value) {} } diff --git a/src/Phalcon/Container.php b/src/Phalcon/Container.php index 73a9f388..22b70ee1 100644 --- a/src/Phalcon/Container.php +++ b/src/Phalcon/Container.php @@ -2,33 +2,38 @@ namespace Phalcon; -use Psr\Container\ContainerInterface; -use Phalcon\DiInterface; - -class Container implements ContainerInterface +/** + * PSR-11 Wrapper for `Phalcon\Di` + */ +class Container implements \Psr\Container\ContainerInterface { - /** - * @var - */ - protected $container; + /** + * @var + */ + protected $container; + + + /** + * Phalcon\Container constructor + * + * @param \Phalcon\Di\DiInterface $container + */ + public function __construct(\Phalcon\Di\DiInterface $container) {} - /** - * Phalcon\Di constructor - */ - public function __construct(DiInterface $container) - { - } + /** + * Return the service + * + * @param mixed $name + * @return mixed + */ + public function get($name) {} - /** - * Return the service - */ - public function get($name) { - } + /** + * Whether a service exists or not in the container + * + * @param mixed $name + * @return bool + */ + public function has($name): bool {} - /** - * Whether a service exists or not in the container - */ - public function has($name) : bool - { - } } diff --git a/src/Phalcon/Crypt.php b/src/Phalcon/Crypt.php index 722ef5af..9a547569 100644 --- a/src/Phalcon/Crypt.php +++ b/src/Phalcon/Crypt.php @@ -3,11 +3,9 @@ namespace Phalcon; /** - * Phalcon\Crypt + * Provides encryption capabilities to Phalcon applications. * - * Provides encryption facilities to Phalcon applications. - * - * + * ```php * use Phalcon\Crypt; * * $crypt = new Crypt(); @@ -20,18 +18,15 @@ * $encrypted = $crypt->encrypt($text, $key); * * echo $crypt->decrypt($encrypted, $key); - * + * ``` */ -class Crypt implements \Phalcon\CryptInterface +class Crypt implements \Phalcon\Crypt\CryptInterface { - const PADDING_DEFAULT = 0; - - const PADDING_ANSI_X_923 = 1; - const PADDING_PKCS7 = 2; + const PADDING_DEFAULT = 0; const PADDING_ISO_10126 = 3; @@ -40,19 +35,43 @@ class Crypt implements \Phalcon\CryptInterface const PADDING_ISO_IEC_7816_4 = 4; - const PADDING_ZERO = 5; + const PADDING_PKCS7 = 2; const PADDING_SPACE = 6; - protected $_key; + const PADDING_ZERO = 5; + /** + * @var string + */ + protected $authTag; - protected $_padding = 0; + /** + * @var string + */ + protected $authData = ''; + + /** + * @var int + */ + protected $authTagLength = 16; + /** + * @var string + */ + protected $key; + + /** + * @var int + */ + protected $padding = 0; - protected $_cipher = 'aes-256-cfb'; + /** + * @var string + */ + protected $cipher = 'aes-256-cfb'; /** * Available cipher methods. @@ -77,224 +96,249 @@ class Crypt implements \Phalcon\CryptInterface /** * Whether calculating message digest enabled or not. - * NOTE: This feature will be enabled by default in Phalcon 4.0.0 * * @var bool */ - protected $useSigning = false; + protected $useSigning = true; + /** + * @return string + */ + public function getAuthTag(): string {} + + /** + * @return string + */ + public function getAuthData(): string {} + + /** + * @return int + */ + public function getAuthTagLength(): int {} + /** * Phalcon\Crypt constructor. * * @param string $cipher * @param bool $useSigning */ - public function __construct($cipher = 'aes-256-cfb', $useSigning = false) {} + public function __construct(string $cipher = 'aes-256-cfb', bool $useSigning = false) {} /** - * Changes the padding scheme used. + * Decrypts an encrypted text. * - * @param int $scheme - * @return \Phalcon\CryptInterface + * ```php + * $encrypted = $crypt->decrypt( + * $encrypted, + * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" + * ); + * ``` + * + * @param string $text + * @param string $key + * @return string */ - public function setPadding($scheme) {} + public function decrypt(string $text, string $key = null): string {} /** - * Sets the cipher algorithm for data encryption and decryption. + * Decrypt a text that is coded as a base64 string. * - * The `aes-256-gcm' is the preferable cipher, but it is not usable - * until the openssl library is upgraded, which is available in PHP 7.1. + * @throws \Phalcon\Crypt\Mismatch + * @param string $text + * @param mixed $key + * @param bool $safe + * @return string + */ + public function decryptBase64(string $text, $key = null, bool $safe = false): string {} + + /** + * Encrypts a text. * - * The `aes-256-ctr' is arguably the best choice for cipher - * algorithm for current openssl library version. + * ```php + * $encrypted = $crypt->encrypt( + * "Top secret", + * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" + * ); + * ``` * - * @param string $cipher - * @return \Phalcon\CryptInterface + * @param string $text + * @param string $key + * @return string */ - public function setCipher($cipher) {} + public function encrypt(string $text, string $key = null): string {} /** - * Returns the current cipher + * Encrypts a text returning the result as a base64 string. * + * @param string $text + * @param mixed $key + * @param bool $safe * @return string */ - public function getCipher() {} + public function encryptBase64(string $text, $key = null, bool $safe = false): string {} /** - * Sets the encryption key. - * - * The `$key' should have been previously generated in a cryptographically safe way. - * - * Bad key: - * "le password" - * - * Better (but still unsafe): - * "#1dj8$=dp?.ak//j1V$~%0X" - * - * Good key: - * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" + * Returns a list of available ciphers. * - * @see \Phalcon\Security\Random - * @param string $key - * @return \Phalcon\CryptInterface + * @return array */ - public function setKey($key) {} + public function getAvailableCiphers(): array {} /** - * Returns the encryption key + * Return a list of registered hashing algorithms suitable for hash_hmac. * - * @return string + * @return array */ - public function getKey() {} + public function getAvailableHashAlgos(): array {} /** - * Set the name of hashing algorithm. + * Returns the current cipher * - * @throws \Phalcon\Crypt\Exception - * @param string $hashAlgo - * @return Crypt + * @return string */ - public function setHashAlgo($hashAlgo) {} + public function getCipher(): string {} /** * Get the name of hashing algorithm. * * @return string */ - public function getHashAlgo() {} + public function getHashAlgo(): string {} /** - * Sets if the calculating message digest must used. - * - * NOTE: This feature will be enabled by default in Phalcon 4.0.0 + * Returns the encryption key * - * @param bool $useSigning - * @return Crypt + * @return string */ - public function useSigning($useSigning) {} + public function getKey(): string {} /** - * Pads texts before encryption. - * - * @link http://www.di-mgt.com.au/cryptopad.html - * @param string $text - * @param string $mode - * @param int $blockSize - * @param int $paddingType + * @param string $tag + * @return \Phalcon\Crypt\CryptInterface */ - protected function _cryptPadText($text, $mode, $blockSize, $paddingType) {} + public function setAuthTag(string $tag): CryptInterface {} /** - * Removes a padding from a text. - * - * If the function detects that the text was not padded, it will return it unmodified. - * - * @param string $text Message to be unpadded - * @param string $mode Encryption mode; unpadding is applied only in CBC or ECB mode - * @param int $blockSize Cipher block size - * @param int $paddingType Padding scheme + * @param string $data + * @return \Phalcon\Crypt\CryptInterface */ - protected function _cryptUnpadText($text, $mode, $blockSize, $paddingType) {} + public function setAuthData(string $data): CryptInterface {} /** - * Encrypts a text. - * - * - * $encrypted = $crypt->encrypt( - * "Top secret", - * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" - * ); - * - * - * @param string $text - * @param string $key - * @return string + * @param int $length + * @return \Phalcon\Crypt\CryptInterface */ - public function encrypt($text, $key = null) {} + public function setAuthTagLength(int $length): CryptInterface {} /** - * Decrypts an encrypted text. + * Sets the cipher algorithm for data encryption and decryption. * - * - * $encrypted = $crypt->decrypt( - * $encrypted, - * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" - * ); - * + * The `aes-256-gcm' is the preferable cipher, but it is not usable + * until the openssl library is upgraded, which is available in PHP 7.1. * - * @throws \Phalcon\Crypt\Mismatch - * @param string $text - * @param string $key - * @return string + * The `aes-256-ctr' is arguably the best choice for cipher + * algorithm for current openssl library version. + * + * @param string $cipher + * @return \Phalcon\Crypt\CryptInterface */ - public function decrypt($text, $key = null) {} + public function setCipher(string $cipher): CryptInterface {} /** - * Encrypts a text returning the result as a base64 string. + * Set the name of hashing algorithm. * - * @param string $text - * @param mixed $key - * @param bool $safe - * @return string + * @throws \Phalcon\Crypt\Exception + * @param string $hashAlgo + * @return \Phalcon\Crypt\CryptInterface */ - public function encryptBase64($text, $key = null, $safe = false) {} + public function setHashAlgo(string $hashAlgo): CryptInterface {} /** - * Decrypt a text that is coded as a base64 string. + * Sets the encryption key. * - * @throws \Phalcon\Crypt\Mismatch - * @param string $text - * @param mixed $key - * @param bool $safe - * @return string + * The `$key' should have been previously generated in a cryptographically + * safe way. + * + * Bad key: + * "le password" + * + * Better (but still unsafe): + * "#1dj8$=dp?.ak//j1V$~%0X" + * + * Good key: + * "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3" + * + * @param string $key + * @return \Phalcon\Crypt\CryptInterface */ - public function decryptBase64($text, $key = null, $safe = false) {} + public function setKey(string $key): CryptInterface {} /** - * Returns a list of available ciphers. + * Changes the padding scheme used. * - * @return array + * @param int $scheme + * @return \Phalcon\Crypt\CryptInterface */ - public function getAvailableCiphers() {} + public function setPadding(int $scheme): CryptInterface {} /** - * Return a list of registered hashing algorithms suitable for hash_hmac. + * Sets if the calculating message digest must used. * - * @return array + * @param bool $useSigning + * @return \Phalcon\Crypt\CryptInterface */ - public function getAvailableHashAlgos() {} + public function useSigning(bool $useSigning): CryptInterface {} /** * Assert the cipher is available. * - * @throws \Phalcon\Crypt\Exception * @param string $cipher */ - protected function assertCipherIsAvailable($cipher) {} + protected function assertCipherIsAvailable(string $cipher) {} /** * Assert the hash algorithm is available. * - * @throws \Phalcon\Crypt\Exception * @param string $hashAlgo */ - protected function assertHashAlgorithmAvailable($hashAlgo) {} + protected function assertHashAlgorithmAvailable(string $hashAlgo) {} /** * Initialize available cipher algorithms. * - * @throws \Phalcon\Crypt\Exception * @param string $cipher * @return int */ - protected function getIvLength($cipher) {} + protected function getIvLength(string $cipher): int {} /** * Initialize available cipher algorithms. - * - * @throws \Phalcon\Crypt\Exception */ protected function initializeAvailableCiphers() {} + /** + * Pads texts before encryption. See [cryptopad](http://www.di-mgt.com.au/cryptopad.html) + * + * @param string $text + * @param string $mode + * @param int $blockSize + * @param int $paddingType + * @return string + */ + protected function cryptPadText(string $text, string $mode, int $blockSize, int $paddingType): string {} + + /** + * Removes a padding from a text. + * + * If the function detects that the text was not padded, it will return it + * unmodified. + * + * @param string $text + * @param string $mode + * @param int $blockSize + * @param int $paddingType + */ + protected function cryptUnpadText(string $text, string $mode, int $blockSize, int $paddingType) {} + } diff --git a/src/Phalcon/CryptInterface.php b/src/Phalcon/CryptInterface.php deleted file mode 100644 index d79c16f8..00000000 --- a/src/Phalcon/CryptInterface.php +++ /dev/null @@ -1,86 +0,0 @@ - - * use Phalcon\Db; - * use Phalcon\Db\Exception; - * use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - * - * try { - * $connection = new MysqlConnection( - * [ - * "host" => "192.168.0.11", - * "username" => "sigma", - * "password" => "secret", - * "dbname" => "blog", - * "port" => "3306", - * ] - * ); - * - * $result = $connection->query( - * "SELECT FROM robots LIMIT 5" - * ); - * - * $result->setFetchMode(Db::FETCH_NUM); - * - * while ($robot = $result->fetch()) { - * print_r($robot); - * } - * } catch (Exception $e) { - * echo $e->getMessage(), PHP_EOL; - * } - * - */ -abstract class Db -{ - - const FETCH_LAZY = 1; - - - const FETCH_ASSOC = 2; - - - const FETCH_NAMED = 11; - - - const FETCH_NUM = 3; - - - const FETCH_BOTH = 4; - - - const FETCH_OBJ = 5; - - - const FETCH_BOUND = 6; - - - const FETCH_COLUMN = 7; - - - const FETCH_CLASS = 8; - - - const FETCH_INTO = 9; - - - const FETCH_FUNC = 10; - - - const FETCH_GROUP = 65536; - - - const FETCH_UNIQUE = 196608; - - - const FETCH_KEY_PAIR = 12; - - - const FETCH_CLASSTYPE = 262144; - - - const FETCH_SERIALIZE = 524288; - - - const FETCH_PROPS_LATE = 1048576; - - - /** - * Enables/disables options in the Database component - * - * @param array $options - */ - public static function setup(array $options) {} - -} diff --git a/src/Phalcon/Debug.php b/src/Phalcon/Debug.php index cfe5cfe6..291d4d30 100644 --- a/src/Phalcon/Debug.php +++ b/src/Phalcon/Debug.php @@ -3,69 +3,90 @@ namespace Phalcon; /** - * Phalcon\Debug - * * Provides debug capabilities to Phalcon applications */ class Debug { - - public $_uri = '//static.phalconphp.com/www/debug/3.0.x/'; - - - public $_theme = 'default'; - - - protected $_hideDocumentRoot = false; - - - protected $_showBackTrace = true; + /** + * @var array + */ + protected $blacklist = array('request' => array(), 'server' => array()); - protected $_showFiles = true; + protected $data; + /** + * @var bool + */ + protected $hideDocumentRoot = false; - protected $_showFileFragment = false; + /** + * @var bool + */ + static protected $isActive; + /** + * @var bool + */ + protected $showBackTrace = true; - protected $_data; + /** + * @var bool + */ + protected $showFileFragment = false; + /** + * @var bool + */ + protected $showFiles = true; - static protected $_isActive; + /** + * @var string + */ + protected $uri = 'https://assets.phalconphp.com/debug/4.0.x/'; /** - * Change the base URI for static resources + * Clears are variables added previously * - * @param string $uri * @return Debug */ - public function setUri($uri) {} + public function clearVars(): Debug {} /** - * Sets if files the exception's backtrace must be showed + * Adds a variable to the debug output * - * @param bool $showBackTrace + * @param mixed $varz + * @param string $key * @return Debug */ - public function setShowBackTrace($showBackTrace) {} + public function debugVar($varz, string $key = null): Debug {} /** - * Set if files part of the backtrace must be shown in the output + * Returns the css sources * - * @param bool $showFiles - * @return Debug + * @return string */ - public function setShowFiles($showFiles) {} + public function getCssSources(): string {} /** - * Sets if files must be completely opened and showed in the output - * or just the fragment related to the exception + * Returns the javascript sources * - * @param bool $showFileFragment - * @return Debug + * @return string */ - public function setShowFileFragment($showFileFragment) {} + public function getJsSources(): string {} + + /** + * Generates a link to the current version documentation + * + * @return string + */ + public function getVersion(): string {} + + /** + * Halts the request showing a backtrace + */ + public function halt() {} /** * Listen for uncaught exceptions and unsilent notices or warnings @@ -74,124 +95,114 @@ public function setShowFileFragment($showFileFragment) {} * @param bool $lowSeverity * @return Debug */ - public function listen($exceptions = true, $lowSeverity = false) {} + public function listen(bool $exceptions = true, bool $lowSeverity = false): Debug {} /** * Listen for uncaught exceptions * * @return Debug */ - public function listenExceptions() {} + public function listenExceptions(): Debug {} /** * Listen for unsilent notices or warnings * * @return Debug */ - public function listenLowSeverity() {} + public function listenLowSeverity(): Debug {} /** - * Halts the request showing a backtrace + * Handles uncaught exceptions + * + * @param \Exception $exception + * @return bool */ - public function halt() {} + public function onUncaughtException(\Exception $exception): bool {} /** - * Adds a variable to the debug output + * Throws an exception when a notice or warning is raised * - * @param mixed $varz - * @param string $key - * @return Debug + * @param mixed $severity + * @param mixed $message + * @param mixed $file + * @param mixed $line + * @param mixed $context */ - public function debugVar($varz, $key = null) {} + public function onUncaughtLowSeverity($severity, $message, $file, $line, $context) {} /** - * Clears are variables added previously + * Sets if files the exception's backtrace must be showed * + * @param array $blacklist * @return Debug */ - public function clearVars() {} + public function setBlacklist(array $blacklist): Debug {} /** - * Escapes a string with htmlentities + * Sets if files the exception's backtrace must be showed * - * @param mixed $value - * @return string + * @param bool $showBackTrace + * @return Debug */ - protected function _escapeString($value) {} + public function setShowBackTrace(bool $showBackTrace): Debug {} /** - * Produces a recursive representation of an array + * Sets if files must be completely opened and showed in the output + * or just the fragment related to the exception * - * @param array $argument - * @param mixed $n - * @return string|null + * @param bool $showFileFragment + * @return Debug */ - protected function _getArrayDump(array $argument, $n = 0) {} + public function setShowFileFragment(bool $showFileFragment): Debug {} /** - * Produces an string representation of a variable + * Set if files part of the backtrace must be shown in the output * - * @param mixed $variable - * @return string + * @param bool $showFiles + * @return Debug */ - protected function _getVarDump($variable) {} + public function setShowFiles(bool $showFiles): Debug {} /** - * Returns the major framework's version + * Change the base URI for static resources * - * @deprecated Will be removed in 4.0.0 - * @see Phalcon\Version::getPart() - * @deprecated - * @return string + * @param string $uri + * @return Debug */ - public function getMajorVersion() {} + public function setUri(string $uri): Debug {} /** - * Generates a link to the current version documentation + * Escapes a string with htmlentities * + * @param mixed $value * @return string */ - public function getVersion() {} + protected function escapeString($value): string {} /** - * Returns the css sources + * Produces a recursive representation of an array * - * @return string + * @param array $argument + * @param mixed $n + * @return string|null */ - public function getCssSources() {} + protected function getArrayDump(array $argument, $n = 0): ?string {} /** - * Returns the javascript sources + * Produces an string representation of a variable * + * @param mixed $variable * @return string */ - public function getJsSources() {} + protected function getVarDump($variable): string {} /** * Shows a backtrace item * * @param int $n * @param array $trace + * @return string */ - protected final function showTraceItem($n, array $trace) {} - - /** - * Throws an exception when a notice or warning is raised - * - * @param mixed $severity - * @param mixed $message - * @param mixed $file - * @param mixed $line - * @param mixed $context - */ - public function onUncaughtLowSeverity($severity, $message, $file, $line, $context) {} - - /** - * Handles uncaught exceptions - * - * @param \Exception $exception - * @return bool - */ - public function onUncaughtException(\Exception $exception) {} + final protected function showTraceItem(int $n, array $trace): string {} } diff --git a/src/Phalcon/Di.php b/src/Phalcon/Di.php index 1ebe86df..4f4d7bb0 100644 --- a/src/Phalcon/Di.php +++ b/src/Phalcon/Di.php @@ -3,23 +3,24 @@ namespace Phalcon; /** - * Phalcon\Di + * Phalcon\Di is a component that implements Dependency Injection/Service + * Location of services and it's itself a container for them. * - * Phalcon\Di is a component that implements Dependency Injection/Service Location - * of services and it's itself a container for them. + * Since Phalcon is highly decoupled, Phalcon\Di is essential to integrate the + * different components of the framework. The developer can also use this + * component to inject dependencies and manage global instances of the different + * classes used in the application. * - * Since Phalcon is highly decoupled, Phalcon\Di is essential to integrate the different - * components of the framework. The developer can also use this component to inject dependencies - * and manage global instances of the different classes used in the application. + * Basically, this component implements the `Inversion of Control` pattern. + * Applying this, the objects do not receive their dependencies using setters or + * constructors, but requesting a service dependency injector. This reduces the + * overall complexity, since there is only one way to get the required + * dependencies within a component. * - * Basically, this component implements the `Inversion of Control` pattern. Applying this, - * the objects do not receive their dependencies using setters or constructors, but requesting - * a service dependency injector. This reduces the overall complexity, since there is only one - * way to get the required dependencies within a component. + * Additionally, this pattern increases testability in the code, thus making it + * less prone to errors. * - * Additionally, this pattern increases testability in the code, thus making it less prone to errors. - * - * + * ```php * use Phalcon\Di; * use Phalcon\Http\Request; * @@ -37,31 +38,26 @@ * ); * * $request = $di->getRequest(); - * + * ``` */ -class Di implements \Phalcon\DiInterface +class Di implements \Phalcon\Di\DiInterface { /** * List of registered services */ - protected $_services; + protected $services; /** * List of shared instances */ - protected $_sharedInstances; - - /** - * To know if the latest resolved instance was shared or not - */ - protected $_freshInstance = false; + protected $sharedInstances; /** * Events Manager * - * @var \Phalcon\Events\ManagerInterface + * @var ManagerInterface */ - protected $_eventsManager; + protected $eventsManager; /** * Latest DI build @@ -75,66 +71,48 @@ class Di implements \Phalcon\DiInterface public function __construct() {} /** - * Sets the internal event manager - * - * @param \Phalcon\Events\ManagerInterface $eventsManager - */ - public function setInternalEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} - - /** - * Returns the internal event manager + * Magic method to get or set services using setters/getters * - * @return \Phalcon\Events\ManagerInterface + * @param string $method + * @param array $arguments + * @return mixed|null */ - public function getInternalEventsManager() {} + public function __call(string $method, array $arguments = array()): ? {} /** - * Registers a service in the services container + * Attempts to register a service in the services container + * Only is successful if a service hasn't been registered previously + * with the same name * * @param string $name * @param mixed $definition * @param bool $shared - * @return \Phalcon\Di\ServiceInterface - */ - public function set($name, $definition, $shared = false) {} - - /** - * Registers an "always shared" service in the services container - * - * @param string $name - * @param mixed $definition - * @return \Phalcon\Di\ServiceInterface + * @return bool|\Phalcon\Di\ServiceInterface */ - public function setShared($name, $definition) {} + public function attempt(string $name, $definition, bool $shared = false) {} /** - * Removes a service in the services container - * It also removes any shared instance created for the service + * Resolves the service based on its configuration * * @param string $name + * @param mixed $parameters + * @return mixed */ - public function remove($name) {} + public function get(string $name, $parameters = null) {} /** - * Attempts to register a service in the services container - * Only is successful if a service hasn't been registered previously - * with the same name + * Return the latest DI created * - * @param string $name - * @param mixed $definition - * @param bool $shared - * @return bool|\Phalcon\Di\ServiceInterface + * @return null|\Phalcon\Di\DiInterface */ - public function attempt($name, $definition, $shared = false) {} + public static function getDefault(): ?DiInterface {} /** - * Sets a service using a raw Phalcon\Di\Service definition + * Returns the internal event manager * - * @param string $name - * @param \Phalcon\Di\ServiceInterface $rawDefinition - * @return \Phalcon\Di\ServiceInterface + * @return \Phalcon\Events\ManagerInterface */ - public function setRaw($name, \Phalcon\Di\ServiceInterface $rawDefinition) {} + public function getInternalEventsManager(): ManagerInterface {} /** * Returns a service definition without resolving @@ -142,7 +120,7 @@ public function setRaw($name, \Phalcon\Di\ServiceInterface $rawDefinition) {} * @param string $name * @return mixed */ - public function getRaw($name) {} + public function getRaw(string $name) {} /** * Returns a Phalcon\Di\Service instance @@ -150,76 +128,118 @@ public function getRaw($name) {} * @param string $name * @return \Phalcon\Di\ServiceInterface */ - public function getService($name) {} + public function getService(string $name): ServiceInterface {} /** - * Resolves the service based on its configuration + * Return the services registered in the DI * - * @param string $name - * @param mixed $parameters - * @return mixed + * @return array|\Phalcon\Di\ServiceInterface[] */ - public function get($name, $parameters = null) {} + public function getServices(): array {} /** * Resolves a service, the resolved service is stored in the DI, subsequent * requests for this service will return the same instance * * @param string $name - * @param array $parameters + * @param mixed $parameters * @return mixed */ - public function getShared($name, $parameters = null) {} + public function getShared(string $name, $parameters = null) {} /** - * Check whether the DI contains a service by a name + * Loads services from a Config object. * - * @param string $name - * @return bool + * @param \Phalcon\Config $config */ - public function has($name) {} + protected function loadFromConfig(\Phalcon\Config $config) {} /** - * Check whether the last service obtained via getShared produced a fresh instance or an existing one + * Loads services from a php config file. * - * @return bool - */ - public function wasFreshInstance() {} - - /** - * Return the services registered in the DI + * ```php + * $di->loadFromPhp("path/services.php"); + * ``` + * + * And the services can be specified in the file as: + * + * ```php + * return [ + * 'myComponent' => [ + * 'className' => '\Acme\Components\MyComponent', + * 'shared' => true, + * ], + * 'group' => [ + * 'className' => '\Acme\Group', + * 'arguments' => [ + * [ + * 'type' => 'service', + * 'service' => 'myComponent', + * ], + * ], + * ], + * 'user' => [ + * 'className' => '\Acme\User', + * ], + * ]; + * ``` * - * @return \Phalcon\Di\Service[] + * @link https://docs.phalconphp.com/en/latest/reference/di.html + * @param string $filePath */ - public function getServices() {} + public function loadFromPhp(string $filePath) {} /** - * Check if a service is registered using the array syntax + * Loads services from a yaml file. * - * @param mixed $name - * @return bool + * ```php + * $di->loadFromYaml( + * "path/services.yaml", + * [ + * "!approot" => function ($value) { + * return dirname(__DIR__) . $value; + * } + * ] + * ); + * ``` + * + * And the services can be specified in the file as: + * + * ```php + * myComponent: + * className: \Acme\Components\MyComponent + * shared: true + * + * group: + * className: \Acme\Group + * arguments: + * - type: service + * name: myComponent + * + * user: + * className: \Acme\User + * ``` + * + * @link https://docs.phalconphp.com/en/latest/reference/di.html + * @param string $filePath + * @param array $callbacks */ - public function offsetExists($name) {} + public function loadFromYaml(string $filePath, array $callbacks = null) {} /** - * Allows to register a shared service using the array syntax - * - * - * $di["request"] = new \Phalcon\Http\Request(); - * + * Check whether the DI contains a service by a name * - * @param mixed $name - * @param mixed $definition + * @param string $name * @return bool */ - public function offsetSet($name, $definition) {} + public function has(string $name): bool {} /** * Allows to obtain a shared service using the array syntax * - * + * ```php * var_dump($di["request"]); - * + * ``` * * @param mixed $name * @return mixed @@ -227,57 +247,64 @@ public function offsetSet($name, $definition) {} public function offsetGet($name) {} /** - * Removes a service from the services container using the array syntax + * Check if a service is registered using the array syntax * * @param mixed $name * @return bool */ - public function offsetUnset($name) {} + public function offsetExists($name): bool {} /** - * Magic method to get or set services using setters/getters + * Allows to register a shared service using the array syntax * - * @param string $method - * @param mixed $arguments - * @return mixed|null + * ```php + * $di["request"] = new \Phalcon\Http\Request(); + * ``` + * + * @param mixed $name + * @param mixed $definition */ - public function __call($method, $arguments = null) {} + public function offsetSet($name, $definition) {} + + /** + * Removes a service from the services container using the array syntax + * + * @param mixed $name + */ + public function offsetUnset($name) {} /** * Registers a service provider. * - * - * use Phalcon\DiInterface; + * ```php + * use Phalcon\Di\DiInterface; * use Phalcon\Di\ServiceProviderInterface; * * class SomeServiceProvider implements ServiceProviderInterface * { * public function register(DiInterface $di) * { - * $di->setShared('service', function () { - * // ... - * }); + * $di->setShared( + * 'service', + * function () { + * // ... + * } + * ); * } * } - * + * ``` * * @param \Phalcon\Di\ServiceProviderInterface $provider */ public function register(\Phalcon\Di\ServiceProviderInterface $provider) {} /** - * Set a default dependency injection container to be obtained into static methods - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public static function setDefault(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Return the latest DI created + * Removes a service in the services container + * It also removes any shared instance created for the service * - * @return null|\Phalcon\DiInterface + * @param string $name */ - public static function getDefault() {} + public function remove(string $name) {} /** * Resets the internal default DI @@ -285,82 +312,46 @@ public static function getDefault() {} public static function reset() {} /** - * Loads services from a yaml file. - * - * - * $di->loadFromYaml( - * "path/services.yaml", - * [ - * "!approot" => function ($value) { - * return dirname(__DIR__) . $value; - * } - * ] - * ); - * - * - * And the services can be specified in the file as: - * - * - * myComponent: - * className: \Acme\Components\MyComponent - * shared: true - * - * group: - * className: \Acme\Group - * arguments: - * - type: service - * name: myComponent - * - * user: - * className: \Acme\User - * + * Registers a service in the services container * - * @link https://docs.phalconphp.com/en/latest/reference/di.html - * @param string $filePath - * @param array $callbacks + * @param string $name + * @param mixed $definition + * @param bool $shared + * @return \Phalcon\Di\ServiceInterface */ - public function loadFromYaml($filePath, array $callbacks = null) {} + public function set(string $name, $definition, bool $shared = false): ServiceInterface {} /** - * Loads services from a php config file. + * Set a default dependency injection container to be obtained into static + * methods * - * - * $di->loadFromPhp("path/services.php"); - * - * - * And the services can be specified in the file as: + * @param \Phalcon\Di\DiInterface $container + */ + public static function setDefault(\Phalcon\Di\DiInterface $container) {} + + /** + * Sets the internal event manager * - * - * return [ - * 'myComponent' => [ - * 'className' => '\Acme\Components\MyComponent', - * 'shared' => true, - * ], - * 'group' => [ - * 'className' => '\Acme\Group', - * 'arguments' => [ - * [ - * 'type' => 'service', - * 'service' => 'myComponent', - * ], - * ], - * ], - * 'user' => [ - * 'className' => '\Acme\User', - * ], - * ]; - * + * @param \Phalcon\Events\ManagerInterface $eventsManager + */ + public function setInternalEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + + /** + * Sets a service using a raw Phalcon\Di\Service definition * - * @link https://docs.phalconphp.com/en/latest/reference/di.html - * @param string $filePath + * @param string $name + * @param \Phalcon\Di\ServiceInterface $rawDefinition + * @return \Phalcon\Di\ServiceInterface */ - public function loadFromPhp($filePath) {} + public function setRaw(string $name, \Phalcon\Di\ServiceInterface $rawDefinition): ServiceInterface {} /** - * Loads services from a Config object. + * Registers an "always shared" service in the services container * - * @param \Phalcon\Config $config + * @param string $name + * @param mixed $definition + * @return \Phalcon\Di\ServiceInterface */ - protected function loadFromConfig(\Phalcon\Config $config) {} + public function setShared(string $name, $definition): ServiceInterface {} } diff --git a/src/Phalcon/Escaper.php b/src/Phalcon/Escaper.php index 82b6b066..ea0b9e58 100644 --- a/src/Phalcon/Escaper.php +++ b/src/Phalcon/Escaper.php @@ -5,129 +5,137 @@ /** * Phalcon\Escaper * - * Escapes different kinds of text securing them. By using this component you may - * prevent XSS attacks. + * Escapes different kinds of text securing them. By using this component you + * may prevent XSS attacks. * - * This component only works with UTF-8. The PREG extension needs to be compiled with UTF-8 support. + * This component only works with UTF-8. The PREG extension needs to be compiled + * with UTF-8 support. * - * + * ```php * $escaper = new \Phalcon\Escaper(); * * $escaped = $escaper->escapeCss("font-family: "); * * echo $escaped; // font\2D family\3A \20 \3C Verdana\3E - * + * ``` */ -class Escaper implements \Phalcon\EscaperInterface +class Escaper implements \Phalcon\Escaper\EscaperInterface { + /** + * @var bool + */ + protected $doubleEncode = true; - protected $_encoding = 'utf-8'; - - - protected $_htmlEscapeMap = null; + /** + * @var string + */ + protected $encoding = 'utf-8'; - protected $_htmlQuoteType = 3; + protected $htmlEscapeMap = null; - protected $_doubleEncode = true; + protected $htmlQuoteType = 3; /** - * Sets the encoding to be used by the escaper - * - * - * $escaper->setEncoding("utf-8"); - * + * Detect the character encoding of a string to be handled by an encoder. + * Special-handling for chr(172) and chr(128) to chr(159) which fail to be + * detected by mb_detect_encoding() * - * @param string $encoding + * @param string $str + * @return string|null */ - public function setEncoding($encoding) {} + final public function detectEncoding(string $str): ?string {} /** - * Returns the internal encoding used by the escaper + * Escape CSS strings by replacing non-alphanumeric chars by their + * hexadecimal escaped representation * + * @param string $css * @return string */ - public function getEncoding() {} + public function escapeCss(string $css): string {} /** - * Sets the HTML quoting type for htmlspecialchars + * Escape javascript strings by replacing non-alphanumeric chars by their + * hexadecimal escaped representation * - * - * $escaper->setHtmlQuoteType(ENT_XHTML); - * - * - * @param int $quoteType + * @param string $js + * @return string */ - public function setHtmlQuoteType($quoteType) {} + public function escapeJs(string $js): string {} /** - * Sets the double_encode to be used by the escaper - * - * - * $escaper->setDoubleEncode(false); - * + * Escapes a HTML string. Internally uses htmlspecialchars * - * @param bool $doubleEncode + * @param string $text + * @return string */ - public function setDoubleEncode($doubleEncode) {} + public function escapeHtml(string $text): string {} /** - * Detect the character encoding of a string to be handled by an encoder - * Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() + * Escapes a HTML attribute string * - * @param string $str - * @return string|null + * @param string $attribute + * @return string */ - public final function detectEncoding($str) {} + public function escapeHtmlAttr(string $attribute): string {} /** - * Utility to normalize a string's encoding to UTF-32. + * Escapes a URL. Internally uses rawurlencode * - * @param string $str + * @param string $url * @return string */ - public final function normalizeEncoding($str) {} + public function escapeUrl(string $url): string {} /** - * Escapes a HTML string. Internally uses htmlspecialchars + * Returns the internal encoding used by the escaper * - * @param string $text * @return string */ - public function escapeHtml($text) {} + public function getEncoding(): string {} /** - * Escapes a HTML attribute string + * Utility to normalize a string's encoding to UTF-32. * - * @param string $attribute + * @param string $str * @return string */ - public function escapeHtmlAttr($attribute) {} + final public function normalizeEncoding(string $str): string {} /** - * Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal escaped representation + * Sets the double_encode to be used by the escaper * - * @param string $css - * @return string + * ```php + * $escaper->setDoubleEncode(false); + * ``` + * + * @param bool $doubleEncode */ - public function escapeCss($css) {} + public function setDoubleEncode(bool $doubleEncode) {} /** - * Escape javascript strings by replacing non-alphanumeric chars by their hexadecimal escaped representation + * Sets the encoding to be used by the escaper * - * @param string $js - * @return string + * ```php + * $escaper->setEncoding("utf-8"); + * ``` + * + * @param string $encoding */ - public function escapeJs($js) {} + public function setEncoding(string $encoding) {} /** - * Escapes a URL. Internally uses rawurlencode + * Sets the HTML quoting type for htmlspecialchars * - * @param string $url - * @return string + * ```php + * $escaper->setHtmlQuoteType(ENT_XHTML); + * ``` + * + * @param int $quoteType */ - public function escapeUrl($url) {} + public function setHtmlQuoteType(int $quoteType) {} } diff --git a/src/Phalcon/Exception.php b/src/Phalcon/Exception.php index 95f9e054..1cbf0b74 100644 --- a/src/Phalcon/Exception.php +++ b/src/Phalcon/Exception.php @@ -7,7 +7,13 @@ * * All framework exceptions should use or extend this exception */ -class Exception extends \Exception +class Exception extends Exception implements \Throwable { + /** + * @param string $service + * @return string + */ + public static function containerServiceNotFound(string $service): string {} + } diff --git a/src/Phalcon/Factory.php b/src/Phalcon/Factory.php deleted file mode 100644 index ace96d42..00000000 --- a/src/Phalcon/Factory.php +++ /dev/null @@ -1,15 +0,0 @@ - - * $filter = new \Phalcon\Filter(); - * - * $filter->sanitize("some(one)@exa\\mple.com", "email"); // returns "someone@example.com" - * $filter->sanitize("hello<<", "string"); // returns "hello" - * $filter->sanitize("!100a019", "int"); // returns "100019" - * $filter->sanitize("!100a019.01a", "float"); // returns "100019.01" - * - */ -class Filter implements \Phalcon\FilterInterface -{ - - const FILTER_EMAIL = 'email'; - - - const FILTER_ABSINT = 'absint'; - - - const FILTER_INT = 'int'; - - - const FILTER_INT_CAST = 'int!'; - - - const FILTER_STRING = 'string'; - - - const FILTER_FLOAT = 'float'; - - - const FILTER_FLOAT_CAST = 'float!'; - - - const FILTER_ALPHANUM = 'alphanum'; - - - const FILTER_TRIM = 'trim'; - - - const FILTER_STRIPTAGS = 'striptags'; - - - const FILTER_LOWER = 'lower'; - - - const FILTER_UPPER = 'upper'; - - - const FILTER_URL = 'url'; - - - const FILTER_SPECIAL_CHARS = 'special_chars'; - - - protected $_filters; - - - /** - * Adds a user-defined filter - * - * @param string $name - * @param mixed $handler - * @return \Phalcon\FilterInterface - */ - public function add($name, $handler) {} - - /** - * Sanitizes a value with a specified single or set of filters - * - * @param mixed $value - * @param mixed $filters - * @param bool $noRecursive - * @return mixed - */ - public function sanitize($value, $filters, $noRecursive = false) {} - - /** - * Internal sanitize wrapper to filter_var - * - * @param mixed $value - * @param string $filter - */ - protected function _sanitize($value, $filter) {} - - /** - * Return the user-defined filters in the instance - * - * @return array - */ - public function getFilters() {} - -} diff --git a/src/Phalcon/FilterInterface.php b/src/Phalcon/FilterInterface.php deleted file mode 100644 index 6ffc77e2..00000000 --- a/src/Phalcon/FilterInterface.php +++ /dev/null @@ -1,38 +0,0 @@ - - * $flash->success("The record was successfully deleted"); - * $flash->error("Cannot open the file"); - * - */ -abstract class Flash implements \Phalcon\FlashInterface, \Phalcon\Di\InjectionAwareInterface -{ - - protected $_cssClasses; - - - protected $_implicitFlush = true; - - - protected $_automaticHtml = true; - - - protected $_escaperService = null; - - - protected $_autoescape = true; - - - protected $_dependencyInjector = null; - - - protected $_messages; - - - /** - * Phalcon\Flash constructor - * - * @param mixed $cssClasses - */ - public function __construct($cssClasses = null) {} - - /** - * Returns the autoescape mode in generated html - * - * @return bool - */ - public function getAutoescape() {} - - /** - * Set the autoescape mode in generated html - * - * @param bool $autoescape - * @return Flash - */ - public function setAutoescape($autoescape) {} - - /** - * Returns the Escaper Service - * - * @return EscaperInterface - */ - public function getEscaperService() {} - - /** - * Sets the Escaper Service - * - * @param EscaperInterface $escaperService - * @return Flash - */ - public function setEscaperService(EscaperInterface $escaperService) {} - - /** - * Sets the dependency injector - * - * @param DiInterface $dependencyInjector - * @return Flash - */ - public function setDI(DiInterface $dependencyInjector) {} - - /** - * Returns the internal dependency injector - * - * @return DiInterface - */ - public function getDI() {} - - /** - * Set whether the output must be implicitly flushed to the output or returned as string - * - * @param bool $implicitFlush - * @return FlashInterface - */ - public function setImplicitFlush($implicitFlush) {} - - /** - * Set if the output must be implicitly formatted with HTML - * - * @param bool $automaticHtml - * @return FlashInterface - */ - public function setAutomaticHtml($automaticHtml) {} - - /** - * Set an array with CSS classes to format the messages - * - * @param array $cssClasses - * @return FlashInterface - */ - public function setCssClasses(array $cssClasses) {} - - /** - * Shows a HTML error message - * - * - * $flash->error("This is an error"); - * - * - * @param mixed $message - * @return string - */ - public function error($message) {} - - /** - * Shows a HTML notice/information message - * - * - * $flash->notice("This is an information"); - * - * - * @param mixed $message - * @return string - */ - public function notice($message) {} - - /** - * Shows a HTML success message - * - * - * $flash->success("The process was finished successfully"); - * - * - * @param mixed $message - * @return string - */ - public function success($message) {} - - /** - * Shows a HTML warning message - * - * - * $flash->warning("Hey, this is important"); - * - * - * @param mixed $message - * @return string - */ - public function warning($message) {} - - /** - * Outputs a message formatting it with HTML - * - * - * $flash->outputMessage("error", $message); - * - * - * @param string $type - * @param string|array $message - * @return string|void - */ - public function outputMessage($type, $message) {} - - /** - * Clears accumulated messages when implicit flush is disabled - */ - public function clear() {} - -} diff --git a/src/Phalcon/FlashInterface.php b/src/Phalcon/FlashInterface.php deleted file mode 100644 index 9353fd25..00000000 --- a/src/Phalcon/FlashInterface.php +++ /dev/null @@ -1,49 +0,0 @@ - + * ```php * use Phalcon\Loader; * * // Creates the autoloader @@ -27,144 +26,131 @@ * * // Requiring this class will automatically include file vendor/example/adapter/Some.php * $adapter = new \Example\Adapter\Some(); - * + * ``` */ class Loader implements \Phalcon\Events\EventsAwareInterface { - protected $_eventsManager = null; - - - protected $_foundPath = null; - - - protected $_checkedPath = null; - - - protected $_classes = array(); - - - protected $_extensions = array('php'); + protected $checkedPath = null; + /** + * @var array + */ + protected $classes = array(); - protected $_namespaces = array(); - + /** + * @var array + */ + protected $directories = array(); - protected $_directories = array(); + protected $eventsManager = null; - protected $_files = array(); + /** + * @var array + */ + protected $extensions = array('php'); - protected $_registered = false; + protected $fileCheckingCallback = 'is_file'; + /** + * @var array + */ + protected $files = array(); - protected $fileCheckingCallback = 'is_file'; + /** + * @var bool + */ + protected $foundPath = null; + /** + * @var array + */ + protected $namespaces = array(); /** - * Sets the file check callback. - * - * - * // Default behavior. - * $loader->setFileCheckingCallback("is_file"); - * - * // Faster than `is_file()`, but implies some issues if - * // the file is removed from the filesystem. - * $loader->setFileCheckingCallback("stream_resolve_include_path"); - * - * // Do not check file existence. - * $loader->setFileCheckingCallback(null); - * - * - * @param mixed $callback - * @return Loader + * @var bool */ - public function setFileCheckingCallback($callback = null) {} + protected $registered = false; + /** - * Sets the events manager + * Autoloads the registered classes * - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @param string $className + * @return bool */ - public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + public function autoLoad(string $className): bool {} /** - * Returns the internal event manager + * Get the path the loader is checking for a path * - * @return \Phalcon\Events\ManagerInterface + * @return string */ - public function getEventsManager() {} + public function getCheckedPath(): string {} /** - * Sets an array of file extensions that the loader must try in each attempt to locate the file + * Returns the class-map currently registered in the autoloader * - * @param array $extensions - * @return Loader + * @return array */ - public function setExtensions(array $extensions) {} + public function getClasses(): array {} /** - * Returns the file extensions registered in the loader + * Returns the directories currently registered in the autoloader * * @return array */ - public function getExtensions() {} + public function getDirs(): array {} /** - * Register namespaces and their related directories + * Returns the internal event manager * - * @param array $namespaces - * @param bool $merge - * @return Loader + * @return \Phalcon\Events\ManagerInterface */ - public function registerNamespaces(array $namespaces, $merge = false) {} + public function getEventsManager(): ManagerInterface {} /** - * @param array $namespace + * Returns the file extensions registered in the loader + * * @return array */ - protected function prepareNamespace(array $namespace) {} + public function getExtensions(): array {} /** - * Returns the namespaces currently registered in the autoloader + * Returns the files currently registered in the autoloader * * @return array */ - public function getNamespaces() {} + public function getFiles(): array {} /** - * Register directories in which "not found" classes could be found + * Get the path when a class was found * - * @param array $directories - * @param bool $merge - * @return Loader + * @return string */ - public function registerDirs(array $directories, $merge = false) {} + public function getFoundPath(): string {} /** - * Returns the directories currently registered in the autoloader + * Returns the namespaces currently registered in the autoloader * * @return array */ - public function getDirs() {} + public function getNamespaces(): array {} /** - * Registers files that are "non-classes" hence need a "require". This is very useful for including files that only - * have functions - * - * @param array $files - * @param bool $merge - * @return Loader + * Checks if a file exists and then adds the file by doing virtual require */ - public function registerFiles(array $files, $merge = false) {} + public function loadFiles() {} /** - * Returns the files currently registered in the autoloader + * Register the autoload method * - * @return array + * @param bool $prepend + * @return Loader */ - public function getFiles() {} + public function register(bool $prepend = false): Loader {} /** * Register classes and their locations @@ -173,55 +159,83 @@ public function getFiles() {} * @param bool $merge * @return Loader */ - public function registerClasses(array $classes, $merge = false) {} + public function registerClasses(array $classes, bool $merge = false): Loader {} /** - * Returns the class-map currently registered in the autoloader + * Register directories in which "not found" classes could be found * - * @return array + * @param array $directories + * @param bool $merge + * @return Loader */ - public function getClasses() {} + public function registerDirs(array $directories, bool $merge = false): Loader {} /** - * Register the autoload method + * Registers files that are "non-classes" hence need a "require". This is + * very useful for including files that only have functions * - * @param bool $prepend + * @param array $files + * @param bool $merge * @return Loader */ - public function register($prepend = false) {} + public function registerFiles(array $files, bool $merge = false): Loader {} /** - * Unregister the autoload method + * Register namespaces and their related directories * + * @param array $namespaces + * @param bool $merge * @return Loader */ - public function unregister() {} + public function registerNamespaces(array $namespaces, bool $merge = false): Loader {} /** - * Checks if a file exists and then adds the file by doing virtual require + * Sets the events manager + * + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function loadFiles() {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Autoloads the registered classes + * Sets an array of file extensions that the loader must try in each attempt + * to locate the file * - * @param string $className - * @return bool + * @param array $extensions + * @return Loader */ - public function autoLoad($className) {} + public function setExtensions(array $extensions): Loader {} /** - * Get the path when a class was found + * Sets the file check callback. * - * @return string + * ```php + * // Default behavior. + * $loader->setFileCheckingCallback("is_file"); + * + * // Faster than `is_file()`, but implies some issues if + * // the file is removed from the filesystem. + * $loader->setFileCheckingCallback("stream_resolve_include_path"); + * + * // Do not check file existence. + * $loader->setFileCheckingCallback(null); + * ``` + * + * @param mixed $callback + * @return Loader */ - public function getFoundPath() {} + public function setFileCheckingCallback($callback = null): Loader {} /** - * Get the path the loader is checking for a path + * Unregister the autoload method * - * @return string + * @return Loader + */ + public function unregister(): Loader {} + + /** + * @param array $namespaceName + * @return array */ - public function getCheckedPath() {} + protected function prepareNamespace(array $namespaceName): array {} } diff --git a/src/Phalcon/Logger.php b/src/Phalcon/Logger.php deleted file mode 100644 index 332e012a..00000000 --- a/src/Phalcon/Logger.php +++ /dev/null @@ -1,55 +0,0 @@ - - * $logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log"); - * $logger->log("This is a message"); - * $logger->log(\Phalcon\Logger::ERROR, "This is an error"); - * $logger->error("This is another error"); - * - */ -abstract class Logger -{ - - const SPECIAL = 9; - - - const CUSTOM = 8; - - - const DEBUG = 7; - - - const INFO = 6; - - - const NOTICE = 5; - - - const WARNING = 4; - - - const ERROR = 3; - - - const ALERT = 2; - - - const CRITICAL = 1; - - - const EMERGENCE = 0; - - - const EMERGENCY = 0; - - -} diff --git a/src/Phalcon/Plugin.php b/src/Phalcon/Plugin.php index 5689dbdb..ddc7559e 100644 --- a/src/Phalcon/Plugin.php +++ b/src/Phalcon/Plugin.php @@ -3,12 +3,10 @@ namespace Phalcon; /** - * Phalcon\Plugin - * * This class can be used to provide user plugins an easy access to services * in the application */ -class Plugin extends \Phalcon\Di\Injectable +abstract class Plugin extends \Phalcon\Di\Injectable { } diff --git a/src/Phalcon/Registry.php b/src/Phalcon/Registry.php index 5f4d660d..c86bd440 100644 --- a/src/Phalcon/Registry.php +++ b/src/Phalcon/Registry.php @@ -5,11 +5,11 @@ /** * Phalcon\Registry * - * A registry is a container for storing objects and values in the application space. - * By storing the value in a registry, the same object is always available throughout - * your application. + * A registry is a container for storing objects and values in the application + * space. By storing the value in a registry, the same object is always + * available throughout your application. * - * + * ```php * $registry = new \Phalcon\Registry(); * * // Set value @@ -31,13 +31,13 @@ * unset($registry->something); * // or * unset($registry["something"]); - * + * ``` * * In addition to ArrayAccess, Phalcon\Registry also implements Countable * (count($registry) will return the number of elements in the registry), - * Serializable and Iterator (you can iterate over the registry - * using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable - * interface is implemented. + * Serializable and Iterator (you can iterate over the registry using a foreach + * loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is + * implemented. * * Phalcon\Registry is very fast (it is typically faster than any userspace * implementation of the registry); however, this comes at a price: @@ -49,112 +49,186 @@ * is several times slower than $registry->property. * * Internally all the magic methods (and interfaces except JsonSerializable) - * are implemented using object handlers or similar techniques: this allows - * to bypass relatively slow method calls. + * are implemented using object handlers or similar techniques: this allows to + * bypass relatively slow method calls. */ -final class Registry implements \ArrayAccess, \Countable, \Iterator +final class Registry extends \Phalcon\Collection { - protected $_data; - - /** - * Registry constructor + * Constructor + * + * @param array $data */ - public final function __construct() {} + final public function __construct(array $data = null) {} /** - * Checks if the element is present in the registry + * Magic getter to get an element from the collection * - * @param mixed $offset - * @return bool + * @param string $element + * @return mixed */ - public final function offsetExists($offset) {} + final public function __get(string $element) {} /** - * Returns an index in the registry + * Magic isset to check whether an element exists or not * - * @param mixed $offset - * @return mixed + * @param string $element + * @return bool */ - public final function offsetGet($offset) {} + final public function __isset(string $element): bool {} /** - * Sets an element in the registry + * Magic setter to assign values to an element * - * @param mixed $offset + * @param string $element * @param mixed $value */ - public final function offsetSet($offset, $value) {} + final public function __set(string $element, $value) {} /** - * Unsets an element in the registry + * Magic unset to remove an element from the collection * - * @param mixed $offset + * @param string $element + */ + final public function __unset(string $element) {} + + /** + * Clears the internal collection */ - public final function offsetUnset($offset) {} + final public function clear() {} /** - * Checks how many elements are in the register + * Count elements of an object * + * @link https://php.net/manual/en/countable.count.php * @return int */ - public final function count() {} + final public function count(): int {} + + /** + * Get the element from the collection + * + * @param string $element + * @param mixed $defaultValue + * @return mixed + */ + final public function get(string $element, $defaultValue = null) {} /** - * Moves cursor to next row in the registry + * Returns the iterator of the class + * + * @return \Traversable */ - public final function next() {} + final public function getIterator(): Traversable {} /** - * Gets pointer number of active row in the registry + * Get the element from the collection * - * @return int + * @param string $element + * @return bool */ - public final function key() {} + final public function has(string $element): bool {} /** - * Rewinds the registry cursor to its beginning + * Initialize internal array + * + * @param array $data + */ + final public function init(array $data = array()) {} + + /** + * Specify data which should be serialized to JSON + * + * @link https://php.net/manual/en/jsonserializable.jsonserialize.php + * @return array */ - public final function rewind() {} + final public function jsonSerialize(): array {} /** - * Checks if the iterator is valid + * Whether a offset exists * + * @link https://php.net/manual/en/arrayaccess.offsetexists.php + * @param mixed $element * @return bool */ - public function valid() {} + final public function offsetExists($element): bool {} + + /** + * Offset to retrieve + * + * @link https://php.net/manual/en/arrayaccess.offsetget.php + * @param mixed $element + * @return mixed + */ + final public function offsetGet($element) {} + + /** + * Offset to set + * + * @link https://php.net/manual/en/arrayaccess.offsetset.php + * @param mixed $element + * @param mixed $value + */ + final public function offsetSet($element, $value) {} + + /** + * Offset to unset + * + * @link https://php.net/manual/en/arrayaccess.offsetunset.php + * @param mixed $element + */ + final public function offsetUnset($element) {} + + /** + * Delete the element from the collection + * + * @param string $element + */ + final public function remove(string $element) {} /** - * Obtains the current value in the internal iterator + * String representation of object + * + * @link https://php.net/manual/en/serializable.serialize.php + * @return string */ - public function current() {} + final public function serialize(): string {} /** - * Sets an element in the registry + * Set an element in the collection * - * @param string $key + * @param string $element * @param mixed $value */ - public final function __set($key, $value) {} + final public function set(string $element, $value) {} /** - * Returns an index in the registry + * Returns the object in an array format * - * @param string $key - * @return mixed + * @return array */ - public final function __get($key) {} + final public function toArray(): array {} /** - * @param string $key - * @return bool + * Returns the object in a JSON format + * + * The default string uses the following options for json_encode + * + * JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_AMP, JSON_HEX_QUOT, JSON_UNESCAPED_SLASHES + * + * @see https://www.ietf.org/rfc/rfc4627.txt + * @param int $options + * @return string */ - public final function __isset($key) {} + final public function toJson(int $options = 79): string {} /** - * @param string $key + * Constructs the object + * + * @link https://php.net/manual/en/serializable.unserialize.php + * @param mixed $serialized */ - public final function __unset($key) {} + final public function unserialize($serialized) {} } diff --git a/src/Phalcon/Security.php b/src/Phalcon/Security.php index 03661177..8a79b6be 100644 --- a/src/Phalcon/Security.php +++ b/src/Phalcon/Security.php @@ -3,11 +3,10 @@ namespace Phalcon; /** - * Phalcon\Security + * This component provides a set of functions to improve the security in Phalcon + * applications * - * This component provides a set of functions to improve the security in Phalcon applications - * - * + * ```php * $login = $this->request->getPost("login"); * $password = $this->request->getPost("password"); * @@ -18,7 +17,7 @@ * // The password is valid * } * } - * + * ``` */ class Security implements \Phalcon\Di\InjectionAwareInterface { @@ -26,15 +25,6 @@ class Security implements \Phalcon\Di\InjectionAwareInterface const CRYPT_DEFAULT = 0; - const CRYPT_STD_DES = 1; - - - const CRYPT_EXT_DES = 2; - - - const CRYPT_MD5 = 3; - - const CRYPT_BLOWFISH = 4; @@ -47,37 +37,49 @@ class Security implements \Phalcon\Di\InjectionAwareInterface const CRYPT_BLOWFISH_Y = 7; + const CRYPT_EXT_DES = 2; + + + const CRYPT_MD5 = 3; + + const CRYPT_SHA256 = 8; const CRYPT_SHA512 = 9; - protected $_dependencyInjector; + const CRYPT_STD_DES = 1; + + + protected $container; - protected $_workFactor = 8; + protected $defaultHash; - protected $_numberBytes = 16; + protected $numberBytes = 16; - protected $_tokenKeySessionID = '$PHALCON/CSRF/KEY$'; + protected $random; - protected $_tokenValueSessionID = '$PHALCON/CSRF$'; + protected $requestToken; - protected $_token; + protected $token; - protected $_tokenKey; + protected $tokenKey; - protected $_random; + protected $tokenKeySessionId = '$PHALCON/CSRF/KEY$'; - protected $_defaultHash; + protected $tokenValueSessionId = '$PHALCON/CSRF$'; + + + protected $workFactor = 8; /** @@ -94,124 +96,129 @@ public function getWorkFactor() {} public function __construct() {} /** - * Sets the dependency injector + * Checks a plain text password and its hash version to check if the + * password matches * - * @param \Phalcon\DiInterface $dependencyInjector + * @param string $password + * @param string $passwordHash + * @param int $maxPassLength + * @return bool */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function checkHash(string $password, string $passwordHash, int $maxPassLength = 0): bool {} /** - * Returns the internal dependency injector + * Check if the CSRF token sent in the request is the same that the current + * in session * - * @return \Phalcon\DiInterface + * @param mixed $tokenKey + * @param mixed $tokenValue + * @param bool $destroyIfValid + * @return bool */ - public function getDI() {} + public function checkToken($tokenKey = null, $tokenValue = null, bool $destroyIfValid = true): bool {} /** - * Sets a number of bytes to be generated by the openssl pseudo random generator + * Computes a HMAC * - * @param long $randomBytes - * @return Security + * @param string $data + * @param string $key + * @param string $algo + * @param bool $raw + * @return string */ - public function setRandomBytes($randomBytes) {} + public function computeHmac(string $data, string $key, string $algo, bool $raw = false): string {} /** - * Returns a number of bytes to be generated by the openssl pseudo random generator + * Removes the value of the CSRF token and key from session * - * @return string + * @return Security */ - public function getRandomBytes() {} + public function destroyToken(): Security {} /** - * Returns a secure random number generator instance + * Returns the default hash * - * @return \Phalcon\Security\Random + * @return int|null */ - public function getRandom() {} + public function getDefaultHash(): ?int {} /** - * Generate a >22-length pseudo random string to be used as salt for passwords + * Returns the internal dependency injector * - * @param int $numberBytes - * @return string + * @return \Phalcon\Di\DiInterface */ - public function getSaltBytes($numberBytes = 0) {} + public function getDI(): DiInterface {} /** - * Creates a password hash using bcrypt with a pseudo random salt + * Returns a secure random number generator instance * - * @param string $password - * @param int $workFactor - * @return string + * @return \Phalcon\Security\Random */ - public function hash($password, $workFactor = 0) {} + public function getRandom(): Random {} /** - * Checks a plain text password and its hash version to check if the password matches + * Returns a number of bytes to be generated by the openssl pseudo random + * generator * - * @param string $password - * @param string $passwordHash - * @param int $maxPassLength - * @return bool + * @return string */ - public function checkHash($password, $passwordHash, $maxPassLength = 0) {} + public function getRandomBytes(): string {} /** - * Checks if a password hash is a valid bcrypt's hash + * Returns the value of the CSRF token for the current request. * - * @param string $passwordHash - * @return bool + * @return string */ - public function isLegacyHash($passwordHash) {} + public function getRequestToken(): string {} /** - * Generates a pseudo random token key to be used as input's name in a CSRF check + * Returns the value of the CSRF token in session * * @return string */ - public function getTokenKey() {} + public function getSessionToken(): string {} /** - * Generates a pseudo random token value to be used as input's value in a CSRF check + * Generate a >22-length pseudo random string to be used as salt for + * passwords * + * @param int $numberBytes * @return string */ - public function getToken() {} + public function getSaltBytes(int $numberBytes = 0): string {} /** - * Check if the CSRF token sent in the request is the same that the current in session + * Generates a pseudo random token value to be used as input's value in a + * CSRF check * - * @param mixed $tokenKey - * @param mixed $tokenValue - * @param bool $destroyIfValid - * @return bool + * @return string */ - public function checkToken($tokenKey = null, $tokenValue = null, $destroyIfValid = true) {} + public function getToken(): string {} /** - * Returns the value of the CSRF token in session + * Generates a pseudo random token key to be used as input's name in a CSRF + * check * * @return string */ - public function getSessionToken() {} + public function getTokenKey(): string {} /** - * Removes the value of the CSRF token and key from session + * Creates a password hash using bcrypt with a pseudo random salt * - * @return Security + * @param string $password + * @param int $workFactor + * @return string */ - public function destroyToken() {} + public function hash(string $password, int $workFactor = 0): string {} /** - * Computes a HMAC + * Checks if a password hash is a valid bcrypt's hash * - * @param string $data - * @param string $key - * @param string $algo - * @param bool $raw - * @return string + * @param string $passwordHash + * @return bool */ - public function computeHmac($data, $key, $algo, $raw = false) {} + public function isLegacyHash(string $passwordHash): bool {} /** * Sets the default hash @@ -219,39 +226,22 @@ public function computeHmac($data, $key, $algo, $raw = false) {} * @param int $defaultHash * @return Security */ - public function setDefaultHash($defaultHash) {} + public function setDefaultHash(int $defaultHash): Security {} /** - * Returns the default hash - * - * @return int|null - */ - public function getDefaultHash() {} - - /** - * Testing for LibreSSL + * Sets the dependency injector * - * @deprecated Will be removed in 4.0.0 - * @return bool + * @param \Phalcon\Di\DiInterface $container */ - public function hasLibreSsl() {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Getting OpenSSL or LibreSSL version. - * - * Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. - * This constant show not the current system openssl library version but version PHP was compiled with. + * Sets a number of bytes to be generated by the openssl pseudo random + * generator * - * @deprecated Will be removed in 4.0.0 - * @link https://bugs.php.net/bug.php?id=71143 - * - * - * if ($security->getSslVersionNumber() >= 20105) { - * // ... - * } - * - * @return int + * @param long $randomBytes + * @return Security */ - public function getSslVersionNumber() {} + public function setRandomBytes(int $randomBytes): Security {} } diff --git a/src/Phalcon/Tag.php b/src/Phalcon/Tag.php index cc253c01..75c84096 100644 --- a/src/Phalcon/Tag.php +++ b/src/Phalcon/Tag.php @@ -3,11 +3,9 @@ namespace Phalcon; /** - * Phalcon\Tag - * * Phalcon\Tag is designed to simplify building of HTML tags. * It provides a set of helpers to generate HTML in a dynamic way. - * This component is an abstract class that you can extend to add more helpers. + * This component is a class that you can extend to add more helpers. */ class Tag { @@ -44,539 +42,570 @@ class Tag const XHTML5 = 11; + + static protected $autoEscape = true; + /** - * Pre-assigned values for components + * Framework Dispatcher */ - static protected $_displayValues; + static protected $container; /** - * HTML document title + * Pre-assigned values for components */ - static protected $_documentTitle = null; + static protected $displayValues; - static protected $_documentAppendTitle = null; + static protected $dispatcherService = null; - static protected $_documentPrependTitle = null; + static protected $documentAppendTitle = null; - static protected $_documentTitleSeparator = null; - - - static protected $_documentType = 11; + static protected $documentPrependTitle = null; /** - * Framework Dispatcher + * HTML document title */ - static protected $_dependencyInjector; + static protected $documentTitle = null; - static protected $_urlService = null; + static protected $documentTitleSeparator = null; - static protected $_dispatcherService = null; + static protected $documentType = 11; - static protected $_escaperService = null; + static protected $escaperService = null; - static protected $_autoEscape = true; + static protected $urlService = null; /** - * Obtains the 'escaper' service if required + * Appends a text to current document title * - * @param array $params - * @return EscaperInterface + * @param mixed $title */ - public static function getEscaper(array $params) {} + public static function appendTitle($title) {} /** - * Renders parameters keeping order in their HTML attributes + * Builds a HTML input[type="check"] tag * - * @param string $code - * @param array $attributes + * ```php + * echo Phalcon\Tag::checkField( + * [ + * "terms", + * "value" => "Y", + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {{ check_field("terms") }} + * ``` + * + * @param array $parameters * @return string */ - public static function renderAttributes($code, array $attributes) {} + public static function checkField($parameters): string {} /** - * Sets the dependency injector container. + * Builds a HTML input[type="color"] tag * - * @param DiInterface $dependencyInjector + * @param array $parameters + * @return string */ - public static function setDI(DiInterface $dependencyInjector) {} + public static function colorField($parameters): string {} /** - * Internally gets the request dispatcher + * Builds a HTML input[type="date"] tag * - * @return DiInterface + * ```php + * echo Phalcon\Tag::dateField( + * [ + * "born", + * "value" => "14-12-1980", + * ] + * ); + * ``` + * + * @param array $parameters + * @return string */ - public static function getDI() {} + public static function dateField($parameters): string {} /** - * Returns a URL service from the default DI + * Builds a HTML input[type="datetime"] tag * - * @return \Phalcon\Mvc\UrlInterface + * @param array $parameters + * @return string */ - public static function getUrlService() {} + public static function dateTimeField($parameters): string {} /** - * Returns an Escaper service from the default DI + * Builds a HTML input[type="datetime-local"] tag * - * @return EscaperInterface + * @param array $parameters + * @return string */ - public static function getEscaperService() {} + public static function dateTimeLocalField($parameters): string {} /** - * Set autoescape mode in generated html + * Alias of Phalcon\Tag::setDefault() * - * @param bool $autoescape + * @param string $id + * @param string $value */ - public static function setAutoescape($autoescape) {} + public static function displayTo(string $id, $value) {} /** - * Assigns default values to generated tags by helpers + * Builds a HTML input[type="email"] tag * - * - * // Assigning "peter" to "name" component - * Phalcon\Tag::setDefault("name", "peter"); + * ```php + * echo Phalcon\Tag::emailField("email"); + * ``` * - * // Later in the view - * echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default - * + * @param array $parameters + * @return string + */ + public static function emailField($parameters): string {} + + /** + * Builds a HTML close FORM tag * - * @param string $id - * @param string $value + * @return string */ - public static function setDefault($id, $value) {} + public static function endForm(): string {} /** - * Assigns default values to generated tags by helpers + * Builds a HTML input[type="file"] tag * - * - * // Assigning "peter" to "name" component - * Phalcon\Tag::setDefaults( + * ```php + * echo Phalcon\Tag::fileField("file"); + * ``` + * + * @param array $parameters + * @return string + */ + public static function fileField($parameters): string {} + + /** + * Builds a HTML FORM tag + * + * ```php + * echo Phalcon\Tag::form("posts/save"); + * + * echo Phalcon\Tag::form( * [ - * "name" => "peter", + * "posts/save", + * "method" => "post", * ] * ); + * ``` * - * // Later in the view - * echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default - * + * Volt syntax: + * ```php + * {{ form("posts/save") }} + * {{ form("posts/save", "method": "post") }} + * ``` * - * @param array $values - * @param bool $merge + * @param array $parameters + * @return string */ - public static function setDefaults(array $values, $merge = false) {} + public static function form($parameters): string {} /** - * Alias of Phalcon\Tag::setDefault + * Converts texts into URL-friendly titles * - * @param string $id - * @param string $value + * ```php + * echo Phalcon\Tag::friendlyTitle("These are big important news", "-") + * ``` + * + * @param string $text + * @param string $separator + * @param bool $lowercase + * @param mixed $replace + * @return string */ - public static function displayTo($id, $value) {} + public static function friendlyTitle(string $text, string $separator = '-', bool $lowercase = true, $replace = null): string {} /** - * Check if a helper has a default value set using Phalcon\Tag::setDefault or value from $_POST + * Get the document type declaration of content * - * @param string $name - * @return bool + * @return string */ - public static function hasValue($name) {} + public static function getDocType(): string {} /** - * Every helper calls this function to check whether a component has a predefined - * value using Phalcon\Tag::setDefault or value from $_POST + * Obtains the 'escaper' service if required * - * @param string $name * @param array $params - * @return mixed + * @return null|\Phalcon\Escaper\EscaperInterface */ - public static function getValue($name, $params = null) {} + public static function getEscaper(array $params): ?EscaperInterface {} /** - * Resets the request and internal values to avoid those fields will have any default value. + * Internally gets the request dispatcher * - * @deprecated Will be removed in 4.0.0 - * @deprecated + * @return \Phalcon\Di\DiInterface */ - public static function resetInput() {} + public static function getDI(): DiInterface {} /** - * Builds a HTML A tag using framework conventions - * - * - * echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + * Returns an Escaper service from the default DI * - * echo Phalcon\Tag::linkTo( - * [ - * "signup/register", - * "Register Here!" - * ] - * ); + * @return \Phalcon\Escaper\EscaperInterface + */ + public static function getEscaperService(): EscaperInterface {} + + /** + * Gets the current document title. + * The title will be automatically escaped. * - * echo Phalcon\Tag::linkTo( - * [ - * "signup/register", - * "Register Here!", - * "class" => "btn-primary", - * ] - * ); + * ```php + * Tag::prependTitle('Hello'); + * Tag::setTitle('World'); + * Tag::appendTitle('from Phalcon'); * - * echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + * echo Tag::getTitle(); // Hello World from Phalcon + * echo Tag::getTitle(false); // World from Phalcon + * echo Tag::getTitle(true, false); // Hello World + * echo Tag::getTitle(false, false); // World + * ``` * - * echo Phalcon\Tag::linkTo( - * [ - * "http://phalconphp.com/", - * "Phalcon Home", - * false, - * ] - * ); + * ```php + * {{ get_title() }} + * ``` * - * echo Phalcon\Tag::linkTo( - * [ - * "http://phalconphp.com/", - * "Phalcon Home", - * "local" => false, - * ] - * ); + * @param bool $prepend + * @param bool $append + * @return string + */ + public static function getTitle(bool $prepend = true, bool $append = true): string {} + + /** + * Gets the current document title separator * - * echo Phalcon\Tag::linkTo( - * [ - * "action" => "http://phalconphp.com/", - * "text" => "Phalcon Home", - * "local" => false, - * "target" => "_new" - * ] - * ); + * ```php + * echo Phalcon\Tag::getTitleSeparator(); + * ``` * - * + * ```php + * {{ get_title_separator() }} + * ``` * - * @param array|string $parameters - * @param string $text - * @param boolean $local * @return string */ - public static function linkTo($parameters, $text = null, $local = true) {} + public static function getTitleSeparator(): string {} /** - * Builds generic INPUT tags + * Returns a URL service from the default DI * - * @param string $type - * @param array $parameters - * @param boolean $asValue - * @return string + * @return \Phalcon\Url\UrlInterface */ - static protected final function _inputField($type, $parameters, $asValue = false) {} + public static function getUrlService(): UrlInterface {} /** - * Builds INPUT tags that implements the checked attribute + * Every helper calls this function to check whether a component has a + * predefined value using Phalcon\Tag::setDefault() or value from $_POST * - * @param string $type - * @param array $parameters - * @return string + * @param string $name + * @param array $params + * @return mixed */ - static protected final function _inputFieldChecked($type, $parameters) {} + public static function getValue($name, array $params = array()) {} /** - * Builds a HTML input[type="color"] tag + * Check if a helper has a default value set using Phalcon\Tag::setDefault() + * or value from $_POST * - * @param array $parameters - * @return string + * @param string $name + * @return bool */ - public static function colorField($parameters) {} + public static function hasValue($name): bool {} /** - * Builds a HTML input[type="text"] tag + * Builds a HTML input[type="hidden"] tag * - * - * echo Phalcon\Tag::textField( + * ```php + * echo Phalcon\Tag::hiddenField( * [ * "name", - * "size" => 30, + * "value" => "mike", * ] * ); - * + * ``` * * @param array $parameters * @return string */ - public static function textField($parameters) {} + public static function hiddenField($parameters): string {} /** - * Builds a HTML input[type="number"] tag + * Builds HTML IMG tags * - * - * echo Phalcon\Tag::numericField( + * ```php + * echo Phalcon\Tag::image("img/bg.png"); + * + * echo Phalcon\Tag::image( * [ - * "price", - * "min" => "1", - * "max" => "5", + * "img/photo.jpg", + * "alt" => "Some Photo", * ] * ); - * - * - * @param array $parameters - * @return string - */ - public static function numericField($parameters) {} - - /** - * Builds a HTML input[type="range"] tag - * - * @param array $parameters - * @return string - */ - public static function rangeField($parameters) {} - - /** - * Builds a HTML input[type="email"] tag + * ``` * - * - * echo Phalcon\Tag::emailField("email"); - * + * Volt Syntax: + * ```php + * {{ image("img/bg.png") }} + * {{ image("img/photo.jpg", "alt": "Some Photo") }} + * {{ image("http://static.mywebsite.com/img/bg.png", false) }} + * ``` * * @param array $parameters + * @param bool $local * @return string */ - public static function emailField($parameters) {} + public static function image($parameters = null, bool $local = true): string {} /** - * Builds a HTML input[type="date"] tag + * Builds a HTML input[type="image"] tag * - * - * echo Phalcon\Tag::dateField( + * ```php + * echo Phalcon\Tag::imageInput( * [ - * "born", - * "value" => "14-12-1980", + * "src" => "/img/button.png", * ] * ); - * + * ``` * - * @param array $parameters - * @return string - */ - public static function dateField($parameters) {} - - /** - * Builds a HTML input[type="datetime"] tag + * Volt syntax: + * ```php + * {{ image_input("src": "/img/button.png") }} + * ``` * * @param array $parameters * @return string */ - public static function dateTimeField($parameters) {} + public static function imageInput($parameters): string {} /** - * Builds a HTML input[type="datetime-local"] tag + * Builds a SCRIPT[type="javascript"] tag * - * @param array $parameters - * @return string - */ - public static function dateTimeLocalField($parameters) {} - - /** - * Builds a HTML input[type="month"] tag + * ```php + * echo Phalcon\Tag::javascriptInclude( + * "http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", + * false + * ); * - * @param array $parameters - * @return string - */ - public static function monthField($parameters) {} - - /** - * Builds a HTML input[type="time"] tag + * echo Phalcon\Tag::javascriptInclude("javascript/jquery.js"); + * ``` * - * @param array $parameters - * @return string - */ - public static function timeField($parameters) {} - - /** - * Builds a HTML input[type="week"] tag + * Volt syntax: + * ```php + * {{ javascript_include("http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", false) }} + * {{ javascript_include("javascript/jquery.js") }} + * ``` * * @param array $parameters + * @param bool $local * @return string */ - public static function weekField($parameters) {} + public static function javascriptInclude($parameters = null, bool $local = true): string {} /** - * Builds a HTML input[type="password"] tag + * Builds a HTML A tag using framework conventions * - * - * echo Phalcon\Tag::passwordField( + * ```php + * echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + * + * echo Phalcon\Tag::linkTo( * [ - * "name", - * "size" => 30, + * "signup/register", + * "Register Here!" * ] * ); - * * - * @param array $parameters - * @return string - */ - public static function passwordField($parameters) {} - - /** - * Builds a HTML input[type="hidden"] tag + * echo Phalcon\Tag::linkTo( + * [ + * "signup/register", + * "Register Here!", + * "class" => "btn-primary", + * ] + * ); * - * - * echo Phalcon\Tag::hiddenField( + * echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + * + * echo Phalcon\Tag::linkTo( * [ - * "name", - * "value" => "mike", + * "http://phalconphp.com/", + * "Phalcon Home", + * false, * ] * ); - * * - * @param array $parameters - * @return string - */ - public static function hiddenField($parameters) {} - - /** - * Builds a HTML input[type="file"] tag + * echo Phalcon\Tag::linkTo( + * [ + * "http://phalconphp.com/", + * "Phalcon Home", + * "local" => false, + * ] + * ); + * + * echo Phalcon\Tag::linkTo( + * [ + * "action" => "http://phalconphp.com/", + * "text" => "Phalcon Home", + * "local" => false, + * "target" => "_new" + * ] + * ); * - * - * echo Phalcon\Tag::fileField("file"); - * + * ``` * - * @param array $parameters + * @param array|string $parameters + * @param string $text + * @param bool $local * @return string */ - public static function fileField($parameters) {} + public static function linkTo($parameters, $text = null, $local = true): string {} /** - * Builds a HTML input[type="search"] tag + * Builds a HTML input[type="month"] tag * * @param array $parameters * @return string */ - public static function searchField($parameters) {} + public static function monthField($parameters): string {} /** - * Builds a HTML input[type="tel"] tag + * Builds a HTML input[type="number"] tag * - * @param array $parameters - * @return string - */ - public static function telField($parameters) {} - - /** - * Builds a HTML input[type="url"] tag + * ```php + * echo Phalcon\Tag::numericField( + * [ + * "price", + * "min" => "1", + * "max" => "5", + * ] + * ); + * ``` * * @param array $parameters * @return string */ - public static function urlField($parameters) {} + public static function numericField($parameters): string {} /** - * Builds a HTML input[type="check"] tag + * Builds a HTML input[type="password"] tag * - * - * echo Phalcon\Tag::checkField( + * ```php + * echo Phalcon\Tag::passwordField( * [ - * "terms", - * "value" => "Y", + * "name", + * "size" => 30, * ] * ); - * - * - * Volt syntax: - * - * {{ check_field("terms") }} - * + * ``` * * @param array $parameters * @return string */ - public static function checkField($parameters) {} + public static function passwordField($parameters): string {} + + /** + * Prepends a text to current document title + * + * @param mixed $title + */ + public static function prependTitle($title) {} /** * Builds a HTML input[type="radio"] tag * - * + * ```php * echo Phalcon\Tag::radioField( * [ * "weather", * "value" => "hot", * ] * ); - * + * ``` * * Volt syntax: - * + * ```php * {{ radio_field("Save") }} - * + * ``` * * @param array $parameters * @return string */ - public static function radioField($parameters) {} + public static function radioField($parameters): string {} /** - * Builds a HTML input[type="image"] tag - * - * - * echo Phalcon\Tag::imageInput( - * [ - * "src" => "/img/button.png", - * ] - * ); - * - * - * Volt syntax: - * - * {{ image_input("src": "/img/button.png") }} - * + * Builds a HTML input[type="range"] tag * * @param array $parameters * @return string */ - public static function imageInput($parameters) {} + public static function rangeField($parameters): string {} /** - * Builds a HTML input[type="submit"] tag + * Renders parameters keeping order in their HTML attributes * - * - * echo Phalcon\Tag::submitButton("Save") - * + * @param string $code + * @param array $attributes + * @return string + */ + public static function renderAttributes(string $code, array $attributes): string {} + + /** + * Renders the title with title tags. The title is automaticall escaped * - * Volt syntax: - * - * {{ submit_button("Save") }} - * + * ```php + * Tag::prependTitle('Hello'); + * Tag::setTitle('World'); + * Tag::appendTitle('from Phalcon'); * - * @param array $parameters + * echo Tag::renderTitle(); // Hello World from Phalcon + * echo Tag::renderTitle(false); // World from Phalcon + * echo Tag::renderTitle(true, false); // Hello World + * echo Tag::renderTitle(false, false); // World + * ``` + * + * ```php + * {{ render_title() }} + * ``` + * + * @param bool $prepend + * @param bool $append * @return string */ - public static function submitButton($parameters) {} + public static function renderTitle(bool $prepend = true, bool $append = true): string {} /** - * Builds a HTML SELECT tag using a PHP array for options + * Resets the request and internal values to avoid those fields will have + * any default value. * - * - * echo Phalcon\Tag::selectStatic( - * "status", - * [ - * "A" => "Active", - * "I" => "Inactive", - * ] - * ); - * + * @deprecated Will be removed in 4.0.0 + * @deprecated + */ + public static function resetInput() {} + + /** + * Builds a HTML input[type="search"] tag * * @param array $parameters - * @param array $data * @return string */ - public static function selectStatic($parameters, $data = null) {} + public static function searchField($parameters): string {} /** * Builds a HTML SELECT tag using a Phalcon\Mvc\Model resultset as options * - * + * ```php * echo Phalcon\Tag::select( * [ * "robotId", @@ -584,261 +613,272 @@ public static function selectStatic($parameters, $data = null) {} * "using" => ["id", "name"], * ] * ); - * + * ``` * * Volt syntax: - * + * ```php * {{ select("robotId", robots, "using": ["id", "name"]) }} - * + * ``` * * @param array $parameters * @param array $data * @return string */ - public static function select($parameters, $data = null) {} + public static function select($parameters, $data = null): string {} /** - * Builds a HTML TEXTAREA tag + * Builds a HTML SELECT tag using a PHP array for options * - * - * echo Phalcon\Tag::textArea( + * ```php + * echo Phalcon\Tag::selectStatic( + * "status", * [ - * "comments", - * "cols" => 10, - * "rows" => 4, + * "A" => "Active", + * "I" => "Inactive", * ] * ); - * - * - * Volt syntax: - * - * {{ text_area("comments", "cols": 10, "rows": 4) }} - * + * ``` * * @param array $parameters + * @param array $data * @return string */ - public static function textArea($parameters) {} + public static function selectStatic($parameters, $data = null): string {} /** - * Builds a HTML FORM tag + * Set autoescape mode in generated html * - * - * echo Phalcon\Tag::form("posts/save"); + * @param bool $autoescape + */ + public static function setAutoescape(bool $autoescape) {} + + /** + * Assigns default values to generated tags by helpers * - * echo Phalcon\Tag::form( + * ```php + * // Assigning "peter" to "name" component + * Phalcon\Tag::setDefault("name", "peter"); + * + * // Later in the view + * echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default + * ``` + * + * @param string $id + * @param string $value + */ + public static function setDefault(string $id, $value) {} + + /** + * Assigns default values to generated tags by helpers + * + * ```php + * // Assigning "peter" to "name" component + * Phalcon\Tag::setDefaults( * [ - * "posts/save", - * "method" => "post", + * "name" => "peter", * ] * ); - * * - * Volt syntax: - * - * {{ form("posts/save") }} - * {{ form("posts/save", "method": "post") }} - * + * // Later in the view + * echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default + * ``` * - * @param array $parameters - * @return string + * @param array $values + * @param bool $merge */ - public static function form($parameters) {} + public static function setDefaults(array $values, bool $merge = false) {} /** - * Builds a HTML close FORM tag + * Sets the dependency injector container. * - * @return string + * @param \Phalcon\Di\DiInterface $container */ - public static function endForm() {} + public static function setDI(\Phalcon\Di\DiInterface $container) {} + + /** + * Set the document type of content + * + * @param int $doctype + */ + public static function setDocType(int $doctype) {} /** * Set the title of view content * - * + * ```php * Phalcon\Tag::setTitle("Welcome to my Page"); - * + * ``` * * @param string $title */ - public static function setTitle($title) {} + public static function setTitle(string $title) {} /** * Set the title separator of view content * - * + * ```php * Phalcon\Tag::setTitleSeparator("-"); - * + * ``` * * @param string $titleSeparator */ - public static function setTitleSeparator($titleSeparator) {} + public static function setTitleSeparator(string $titleSeparator) {} /** - * Appends a text to current document title + * Builds a LINK[rel="stylesheet"] tag * - * @param mixed $title - */ - public static function appendTitle($title) {} - - /** - * Prepends a text to current document title + * ```php + * echo Phalcon\Tag::stylesheetLink( + * "http://fonts.googleapis.com/css?family=Rosario", + * false + * ); * - * @param mixed $title + * echo Phalcon\Tag::stylesheetLink("css/style.css"); + * ``` + * + * Volt Syntax: + * ```php + * {{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }} + * {{ stylesheet_link("css/style.css") }} + * ``` + * + * @param array $parameters + * @param bool $local + * @return string */ - public static function prependTitle($title) {} + public static function stylesheetLink($parameters = null, bool $local = true): string {} /** - * Gets the current document title. - * The title will be automatically escaped. + * Builds a HTML input[type="submit"] tag * - * - * echo Phalcon\Tag::getTitle(); - * + * ```php + * echo Phalcon\Tag::submitButton("Save") + * ``` * - * - * {{ get_title() }} - * + * Volt syntax: + * ```php + * {{ submit_button("Save") }} + * ``` * - * @param bool $tags + * @param array $parameters * @return string */ - public static function getTitle($tags = true) {} + public static function submitButton($parameters): string {} /** - * Gets the current document title separator - * - * - * echo Phalcon\Tag::getTitleSeparator(); - * - * - * - * {{ get_title_separator() }} - * + * Builds a HTML tag * + * @param string $tagName + * @param mixed $parameters + * @param bool $selfClose + * @param bool $onlyStart + * @param bool $useEol * @return string */ - public static function getTitleSeparator() {} + public static function tagHtml(string $tagName, $parameters = null, bool $selfClose = false, bool $onlyStart = false, bool $useEol = false): string {} /** - * Builds a LINK[rel="stylesheet"] tag + * Builds a HTML tag closing tag * - * - * echo Phalcon\Tag::stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false); - * echo Phalcon\Tag::stylesheetLink("css/style.css"); - * + * ```php + * echo Phalcon\Tag::tagHtmlClose("script", true); + * ``` * - * Volt Syntax: - * - * {{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }} - * {{ stylesheet_link("css/style.css") }} - * + * @param string $tagName + * @param bool $useEol + * @return string + */ + public static function tagHtmlClose(string $tagName, bool $useEol = false): string {} + + /** + * Builds a HTML input[type="tel"] tag * * @param array $parameters - * @param boolean $local * @return string */ - public static function stylesheetLink($parameters = null, $local = true) {} + public static function telField($parameters): string {} /** - * Builds a SCRIPT[type="javascript"] tag + * Builds a HTML TEXTAREA tag * - * - * echo Phalcon\Tag::javascriptInclude("http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", false); - * echo Phalcon\Tag::javascriptInclude("javascript/jquery.js"); - * + * ```php + * echo Phalcon\Tag::textArea( + * [ + * "comments", + * "cols" => 10, + * "rows" => 4, + * ] + * ); + * ``` * * Volt syntax: - * - * {{ javascript_include("http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", false) }} - * {{ javascript_include("javascript/jquery.js") }} - * + * ```php + * {{ text_area("comments", "cols": 10, "rows": 4) }} + * ``` * * @param array $parameters - * @param boolean $local * @return string */ - public static function javascriptInclude($parameters = null, $local = true) {} + public static function textArea($parameters): string {} /** - * Builds HTML IMG tags - * - * - * echo Phalcon\Tag::image("img/bg.png"); + * Builds a HTML input[type="text"] tag * - * echo Phalcon\Tag::image( + * ```php + * echo Phalcon\Tag::textField( * [ - * "img/photo.jpg", - * "alt" => "Some Photo", + * "name", + * "size" => 30, * ] * ); - * - * - * Volt Syntax: - * - * {{ image("img/bg.png") }} - * {{ image("img/photo.jpg", "alt": "Some Photo") }} - * {{ image("http://static.mywebsite.com/img/bg.png", false) }} - * + * ``` * * @param array $parameters - * @param boolean $local * @return string */ - public static function image($parameters = null, $local = true) {} + public static function textField($parameters): string {} /** - * Converts texts into URL-friendly titles - * - * - * echo Phalcon\Tag::friendlyTitle("These are big important news", "-") - * + * Builds a HTML input[type="time"] tag * - * @param string $text - * @param string $separator - * @param bool $lowercase - * @param mixed $replace + * @param array $parameters * @return string */ - public static function friendlyTitle($text, $separator = '-', $lowercase = true, $replace = null) {} + public static function timeField($parameters): string {} /** - * Set the document type of content + * Builds a HTML input[type="url"] tag * - * @param int $doctype + * @param array $parameters + * @return string */ - public static function setDocType($doctype) {} + public static function urlField($parameters): string {} /** - * Get the document type declaration of content + * Builds a HTML input[type="week"] tag * + * @param array $parameters * @return string */ - public static function getDocType() {} + public static function weekField($parameters): string {} /** - * Builds a HTML tag + * Builds generic INPUT tags * - * @param string $tagName - * @param mixed $parameters - * @param bool $selfClose - * @param bool $onlyStart - * @param bool $useEol + * @param string $type + * @param array $parameters + * @param bool $asValue * @return string */ - public static function tagHtml($tagName, $parameters = null, $selfClose = false, $onlyStart = false, $useEol = false) {} + static final protected function inputField(string $type, $parameters, bool $asValue = false): string {} /** - * Builds a HTML tag closing tag - * - * - * echo Phalcon\Tag::tagHtmlClose("script", true); - * + * Builds INPUT tags that implements the checked attribute * - * @param string $tagName - * @param bool $useEol + * @param string $type + * @param array $parameters * @return string */ - public static function tagHtmlClose($tagName, $useEol = false) {} + static final protected function inputFieldChecked(string $type, $parameters): string {} } diff --git a/src/Phalcon/Text.php b/src/Phalcon/Text.php index 70eb7d2c..14589c93 100644 --- a/src/Phalcon/Text.php +++ b/src/Phalcon/Text.php @@ -3,11 +3,9 @@ namespace Phalcon; /** - * Phalcon\Text - * * Provides utilities to work with texts */ -abstract class Text +class Text { const RANDOM_ALNUM = 0; @@ -16,221 +14,233 @@ abstract class Text const RANDOM_ALPHA = 1; - const RANDOM_HEXDEC = 2; + const RANDOM_DISTINCT = 5; - const RANDOM_NUMERIC = 3; + const RANDOM_HEXDEC = 2; const RANDOM_NOZERO = 4; - const RANDOM_DISTINCT = 5; + const RANDOM_NUMERIC = 3; /** * Converts strings to camelize style * - * + * ```php * echo Phalcon\Text::camelize("coco_bongo"); // CocoBongo * echo Phalcon\Text::camelize("co_co-bon_go", "-"); // Co_coBon_go * echo Phalcon\Text::camelize("co_co-bon_go", "_-"); // CoCoBonGo - * + * ``` * - * @param string $str + * @param string $text * @param mixed $delimiter * @return string */ - public static function camelize($str, $delimiter = null) {} + public static function camelize(string $text, $delimiter = null): string {} /** - * Uncamelize strings which are camelized + * Concatenates strings using the separator only once without duplication in + * places concatenation * - * - * echo Phalcon\Text::uncamelize("CocoBongo"); // coco_bongo - * echo Phalcon\Text::uncamelize("CocoBongo", "-"); // coco-bongo - * - * - * @param string $str - * @param mixed $delimiter - * @return string - */ - public static function uncamelize($str, $delimiter = null) {} - - /** - * Adds a number to a string or increment that number if it already is defined + * ```php + * $str = Phalcon\Text::concat( + * "/", + * "/tmp/", + * "/folder_1/", + * "/folder_2", + * "folder_3/" + * ); * - * - * echo Phalcon\Text::increment("a"); // "a_1" - * echo Phalcon\Text::increment("a_1"); // "a_2" - * + * // /tmp/folder_1/folder_2/folder_3/ + * echo $str; + * ``` * - * @param string $str * @param string $separator + * @param string $a + * @param string $b + * @param string $...N * @return string */ - public static function increment($str, $separator = '_') {} + public static function concat(): string {} /** - * Generates a random string based on the given type. Type is one of the RANDOM_ constants + * Generates random text in accordance with the template * - * - * use Phalcon\Text; + * ```php + * // Hi my name is a Bob + * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * - * // "aloiwkqz" - * echo Text::random(Text::RANDOM_ALNUM); - * + * // Hi my name is a Jon + * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * - * @param int $type - * @param long $length - * @return string - */ - public static function random($type = 0, $length = 8) {} - - /** - * Check if a string starts with a given string + * // Hello my name is a Bob + * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); * - * - * echo Phalcon\Text::startsWith("Hello", "He"); // true - * echo Phalcon\Text::startsWith("Hello", "he", false); // false - * echo Phalcon\Text::startsWith("Hello", "he"); // true - * + * // Hello my name is a Zyxep + * echo Phalcon\Text::dynamic( + * "[Hi/Hello], my name is a [Zyxep/Mark]!", + * "[", "]", + * "/" + * ); + * ``` * - * @param string $str - * @param string $start - * @param bool $ignoreCase - * @return bool + * @param string $text + * @param string $leftDelimiter + * @param string $rightDelimiter + * @param string $separator + * @return string */ - public static function startsWith($str, $start, $ignoreCase = true) {} + public static function dynamic(string $text, string $leftDelimiter = '{', string $rightDelimiter = '}', string $separator = '|'): string {} /** * Check if a string ends with a given string * - * + * ```php * echo Phalcon\Text::endsWith("Hello", "llo"); // true * echo Phalcon\Text::endsWith("Hello", "LLO", false); // false * echo Phalcon\Text::endsWith("Hello", "LLO"); // true - * + * ``` * - * @param string $str + * @param string $text * @param string $end * @param bool $ignoreCase * @return bool */ - public static function endsWith($str, $end, $ignoreCase = true) {} + public static function endsWith(string $text, string $end, bool $ignoreCase = true): bool {} /** - * Lowercases a string, this function makes use of the mbstring extension if available + * Makes an underscored or dashed phrase human-readable * - * - * echo Phalcon\Text::lower("HELLO"); // hello - * + * ```php + * echo Phalcon\Text::humanize("start-a-horse"); // "start a horse" + * echo Phalcon\Text::humanize("five_cats"); // "five cats" + * ``` * - * @param string $str - * @param string $encoding + * @param string $text * @return string */ - public static function lower($str, $encoding = 'UTF-8') {} + public static function humanize(string $text): string {} /** - * Uppercases a string, this function makes use of the mbstring extension if available + * Adds a number to a string or increment that number if it already is + * defined * - * - * echo Phalcon\Text::upper("hello"); // HELLO - * + * ```php + * echo Phalcon\Text::increment("a"); // "a_1" + * echo Phalcon\Text::increment("a_1"); // "a_2" + * ``` * - * @param string $str - * @param string $encoding + * @param string $text + * @param string $separator * @return string */ - public static function upper($str, $encoding = 'UTF-8') {} + public static function increment(string $text, string $separator = '_'): string {} /** - * Reduces multiple slashes in a string to single slashes + * Lowercases a string, this function makes use of the mbstring extension if + * available * - * - * echo Phalcon\Text::reduceSlashes("foo//bar/baz"); // foo/bar/baz - * echo Phalcon\Text::reduceSlashes("http://foo.bar///baz/buz"); // http://foo.bar/baz/buz - * + * ```php + * echo Phalcon\Text::lower("HELLO"); // hello + * ``` * - * @param string $str + * @param string $text + * @param string $encoding * @return string */ - public static function reduceSlashes($str) {} + public static function lower(string $text, string $encoding = 'UTF-8'): string {} /** - * Concatenates strings using the separator only once without duplication in places concatenation + * Check if a string starts with a given string * - * - * $str = Phalcon\Text::concat( - * "/", - * "/tmp/", - * "/folder_1/", - * "/folder_2", - * "folder_3/" - * ); + * ```php + * echo Phalcon\Text::startsWith("Hello", "He"); // true + * echo Phalcon\Text::startsWith("Hello", "he", false); // false + * echo Phalcon\Text::startsWith("Hello", "he"); // true + * ``` * - * // /tmp/folder_1/folder_2/folder_3/ - * echo $str; - * + * @param string $text + * @param string $start + * @param bool $ignoreCase + * @return bool + */ + public static function startsWith(string $text, string $start, bool $ignoreCase = true): bool {} + + /** + * Generates a random string based on the given type. Type is one of the + * RANDOM_ constants * - * @param string $separator - * @param string $a - * @param string $b - * @param string $...N + * ```php + * use Phalcon\Text; + * + * // "aloiwkqz" + * echo Text::random(Text::RANDOM_ALNUM); + * ``` + * + * @param int $type + * @param long $length * @return string */ - public static function concat() {} + public static function random(int $type = 0, int $length = 8): string {} /** - * Generates random text in accordance with the template + * Reduces multiple slashes in a string to single slashes * - * - * // Hi my name is a Bob - * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); + * ```php + * // foo/bar/baz + * echo Phalcon\Text::reduceSlashes("foo//bar/baz"); * - * // Hi my name is a Jon - * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); + * // http://foo.bar/baz/buz + * echo Phalcon\Text::reduceSlashes("http://foo.bar///baz/buz"); + * ``` * - * // Hello my name is a Bob - * echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); + * @param string $text + * @return string + */ + public static function reduceSlashes(string $text): string {} + + /** + * Uncamelize strings which are camelized * - * // Hello my name is a Zyxep - * echo Phalcon\Text::dynamic("[Hi/Hello], my name is a [Zyxep/Mark]!", "[", "]", "/"); - * + * ```php + * echo Phalcon\Text::uncamelize("CocoBongo"); // coco_bongo + * echo Phalcon\Text::uncamelize("CocoBongo", "-"); // coco-bongo + * ``` * * @param string $text - * @param string $leftDelimiter - * @param string $rightDelimiter - * @param string $separator + * @param mixed $delimiter * @return string */ - public static function dynamic($text, $leftDelimiter = '{', $rightDelimiter = '}', $separator = '|') {} + public static function uncamelize(string $text, $delimiter = null): string {} /** * Makes a phrase underscored instead of spaced * - * + * ```php * echo Phalcon\Text::underscore("look behind"); // "look_behind" * echo Phalcon\Text::underscore("Awesome Phalcon"); // "Awesome_Phalcon" - * + * ``` * * @param string $text * @return string */ - public static function underscore($text) {} + public static function underscore(string $text): string {} /** - * Makes an underscored or dashed phrase human-readable + * Uppercases a string, this function makes use of the mbstring extension if + * available * - * - * echo Phalcon\Text::humanize("start-a-horse"); // "start a horse" - * echo Phalcon\Text::humanize("five_cats"); // "five cats" - * + * ```php + * echo Phalcon\Text::upper("hello"); // HELLO + * ``` * * @param string $text + * @param string $encoding * @return string */ - public static function humanize($text) {} + public static function upper(string $text, string $encoding = 'UTF-8'): string {} } diff --git a/src/Phalcon/Translate.php b/src/Phalcon/Translate.php deleted file mode 100644 index ad8cc91c..00000000 --- a/src/Phalcon/Translate.php +++ /dev/null @@ -1,14 +0,0 @@ - + * ```php * // Generate a URL appending the URI to the base URI * echo $url->get("products/edit/1"); * @@ -26,163 +17,174 @@ * "year" => "2012", * ] * ); - * + * ``` */ -class Url implements UrlInterface, InjectionAwareInterface +class Url implements \Phalcon\Url\UrlInterface, \Phalcon\Di\InjectionAwareInterface { + /** + * @var null | string + */ + protected $baseUri = null; + + /** + * @var null | string + */ + protected $basePath = null; + + /** + * @var + */ + protected $container; + + + protected $router; + + /** + * @var null | string + */ + protected $staticBaseUri = null; + + + /** + * Generates a URL + * + * ```php + * // Generate a URL appending the URI to the base URI + * echo $url->get("products/edit/1"); + * + * // Generate a URL for a predefined route + * echo $url->get( + * [ + * "for" => "blog-post", + * "title" => "some-cool-stuff", + * "year" => "2015", + * ] + * ); + * + * // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + * echo $url->get( + * "show/products", + * [ + * "id" => 1, + * "name" => "Carrots", + * ] + * ); + * + * // Generate an absolute URL by setting the third parameter as false. + * echo $url->get( + * "https://phalconphp.com/", + * null, + * false + * ); + * ``` + * + * @param mixed $uri + * @param mixed $args + * @param bool $local + * @param mixed $baseUri + * @return string + */ + public function get($uri = null, $args = null, bool $local = null, $baseUri = null): string {} + + /** + * Returns the base path + * + * @return string + */ + public function getBasePath(): string {} + + /** + * Returns the prefix for all the generated urls. By default / + * + * @return string + */ + public function getBaseUri(): string {} + + /** + * Returns the DependencyInjector container + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Generates a URL for a static resource + * + * ```php + * // Generate a URL for a static resource + * echo $url->getStatic("img/logo.png"); + * + * // Generate a URL for a static predefined route + * echo $url->getStatic( + * [ + * "for" => "logo-cdn", + * ] + * ); + * ``` + * + * @param mixed $uri + * @return string + */ + public function getStatic($uri = null): string {} + + /** + * Returns the prefix for all the generated static urls. By default / + * + * @return string + */ + public function getStaticBaseUri(): string {} + + /** + * Sets a base path for all the generated paths + * + * ```php + * $url->setBasePath("/var/www/htdocs/"); + * ``` + * + * @param string $basePath + * @return \Phalcon\Url\UrlInterface + */ + public function setBasePath(string $basePath): UrlInterface {} + + /** + * Sets a prefix for all the URIs to be generated + * + * ```php + * $url->setBaseUri("/invo/"); + * + * $url->setBaseUri("/invo/index.php/"); + * ``` + * + * @param string $baseUri + * @return \Phalcon\Url\UrlInterface + */ + public function setBaseUri(string $baseUri): UrlInterface {} + + /** + * Sets the DependencyInjector container + * + * @param \Phalcon\Di\DiInterface $container + */ + public function setDI(\Phalcon\Di\DiInterface $container) {} + + /** + * Sets a prefix for all static URLs generated + * + * ```php + * $url->setStaticBaseUri("/invo/"); + * ``` + * + * @param string $staticBaseUri + * @return \Phalcon\Url\UrlInterface + */ + public function setStaticBaseUri(string $staticBaseUri): UrlInterface {} + + /** + * Generates a local path + * + * @param string $path + * @return string + */ + public function path(string $path = null): string {} - /** - * @var null | string - */ - protected $baseUri = null; - - /** - * @var null | string - */ - protected $basePath = null; - - /** - * @var - */ - protected $container; - - protected $router; - - /** - * @var null | string - */ - protected $staticBaseUri = null; - - /** - * Generates a URL - * - * - * // Generate a URL appending the URI to the base URI - * echo $url->get("products/edit/1"); - * - * // Generate a URL for a predefined route - * echo $url->get( - * [ - * "for" => "blog-post", - * "title" => "some-cool-stuff", - * "year" => "2015", - * ] - * ); - * - * // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - * echo $url->get( - * "show/products", - * [ - * "id" => 1, - * "name" => "Carrots", - * ] - * ); - * - * // Generate an absolute URL by setting the third parameter as false. - * echo $url->get( - * "https://phalconphp.com/", - * null, - * false - * ); - * - */ - public function get($uri = null, $args = null, bool $local = null, $baseUri = null) : string - { - } - - /** - * Returns the base path - */ - public function getBasePath() : string - { - } - - /** - * Returns the prefix for all the generated urls. By default / - */ - public function getBaseUri() : string - { - } - - /** - * Returns the DependencyInjector container - */ - public function getDI() : DiInterface - { - } - - /** - * Generates a URL for a static resource - * - * - * // Generate a URL for a static resource - * echo $url->getStatic("img/logo.png"); - * - * // Generate a URL for a static predefined route - * echo $url->getStatic( - * [ - * "for" => "logo-cdn", - * ] - * ); - * - */ - public function getStatic($uri = null) : string - { - } - - /** - * Returns the prefix for all the generated static urls. By default / - */ - public function getStaticBaseUri() : string - { - } - - /** - * Sets a base path for all the generated paths - * - * - * $url->setBasePath("/var/www/htdocs/"); - * - */ - public function setBasePath(string $basePath) : UrlInterface - { - } - - /** - * Sets a prefix for all the URIs to be generated - * - * - * $url->setBaseUri("/invo/"); - * - * $url->setBaseUri("/invo/index.php/"); - * - */ - public function setBaseUri(string $baseUri) : UrlInterface - { - } - - /** - * Sets the DependencyInjector container - */ - public function setDI(DiInterface $dependencyInjector) - { - } - - /** - * Sets a prefix for all static URLs generated - * - * - * $url->setStaticBaseUri("/invo/"); - * - */ - public function setStaticBaseUri(string $staticBaseUri) : UrlInterface - { - } - - /** - * Generates a local path - */ - public function path(string $path = null) : string - { - } } diff --git a/src/Phalcon/Urlinterface.php b/src/Phalcon/Urlinterface.php deleted file mode 100644 index d107d252..00000000 --- a/src/Phalcon/Urlinterface.php +++ /dev/null @@ -1,44 +0,0 @@ - + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_MAJOR * ); - * + * ``` */ const VERSION_MAJOR = 0; /** * The constant referencing the major version. Returns 1 * - * + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_MEDIUM * ); - * + * ``` */ const VERSION_MEDIUM = 1; /** * The constant referencing the major version. Returns 2 * - * + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_MINOR * ); - * + * ``` */ const VERSION_MINOR = 2; /** * The constant referencing the major version. Returns 3 * - * + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_SPECIAL * ); - * + * ``` */ const VERSION_SPECIAL = 3; /** * The constant referencing the major version. Returns 4 * - * + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_SPECIAL_NUMBER * ); - * + * ``` */ const VERSION_SPECIAL_NUMBER = 4; @@ -72,58 +70,56 @@ class Version * A - Major version * B - Med version (two digits) * C - Min version (two digits) - * D - Special release: 1 = Alpha, 2 = Beta, 3 = RC, 4 = Stable + * D - Special release: 1 = alpha, 2 = beta, 3 = RC, 4 = stable * E - Special release version i.e. RC1, Beta2 etc. * * @return array */ - protected static function _getVersion() {} + protected static function _getVersion(): array {} /** - * Translates a number to a special release - * - * If Special release = 1 this function will return ALPHA + * Translates a number to a special release. * * @param int $special * @return string */ - protected final static function _getSpecial($special) {} + protected final static function _getSpecial(int $special): string {} /** * Returns the active version (string) * - * + * ```php * echo Phalcon\Version::get(); - * + * ``` * * @return string */ - public static function get() {} + public static function get(): string {} /** * Returns the numeric active version * - * + * ```php * echo Phalcon\Version::getId(); - * + * ``` * * @return string */ - public static function getId() {} + public static function getId(): string {} /** * Returns a specific part of the version. If the wrong parameter is passed * it will return the full version * - * + * ```php * echo Phalcon\Version::getPart( * Phalcon\Version::VERSION_MAJOR * ); - * + * ``` * * @param int $part * @return string */ - public static function getPart($part) {} + public static function getPart(int $part): string {} } diff --git a/src/Phalcon/acl/Component.php b/src/Phalcon/acl/Component.php index 0730e294..4928abdd 100644 --- a/src/Phalcon/acl/Component.php +++ b/src/Phalcon/acl/Component.php @@ -2,46 +2,53 @@ namespace Phalcon\Acl; -use Phalcon\Acl\Exception; - /** - * Phalcon\Acl\Component - * * This class defines component entity and its description */ -class Component implements ComponentInterface +class Component implements \Phalcon\Acl\ComponentInterface { - /** - * Component description - * @var string - */ - private $description; - - /** - * Component name - * @var string - */ - private $name; + /** + * Component description + * + * @var string + */ + private $description; /** - * Phalcon\Acl\Component constructor - * @param string $name - * @param string|null $description + * Component name + * + * @var string */ - public function __construct(string $name, string $description = null) {} + private $name; + /** - * Returns component description + * Component description + * + * @return string */ public function getDescription(): string {} /** - * Returns the component name + * Component name + * + * @return string */ public function getName(): string {} /** - * Magic method __toString + * Component name + * + * @return string */ public function __toString(): string {} + + /** + * Phalcon\Acl\Component constructor + * + * @param string $name + * @param string $description + */ + public function __construct(string $name, string $description = null) {} + } diff --git a/src/Phalcon/acl/Componentaware.php b/src/Phalcon/acl/ComponentAware.php similarity index 66% rename from src/Phalcon/acl/Componentaware.php rename to src/Phalcon/acl/ComponentAware.php index 1f191edd..3539eb59 100644 --- a/src/Phalcon/acl/Componentaware.php +++ b/src/Phalcon/acl/ComponentAware.php @@ -3,14 +3,16 @@ namespace Phalcon\Acl; /** - * Phalcon\Acl\ComponentAware - * * Interface for classes which could be used in allow method as RESOURCE */ interface ComponentAware { + /** * Returns component name - */ - public function getComponentName() : string; + * + * @return string + */ + public function getComponentName(): string; + } diff --git a/src/Phalcon/acl/ComponentInterface.php b/src/Phalcon/acl/ComponentInterface.php new file mode 100644 index 00000000..b1e0960c --- /dev/null +++ b/src/Phalcon/acl/ComponentInterface.php @@ -0,0 +1,32 @@ +setDefaultAction( - * \Phalcon\Acl::DENY + * \Phalcon\Acl\Enum::DENY * ); * * // Register roles @@ -56,9 +51,9 @@ * } * * // Grant access to public areas to both users and guests - * foreach ($roles as $role){ + * foreach ($roles as $role) { * foreach ($publicComponents as $component => $actions) { - * $acl->allow($role->getName(), $component, "*"); + * $acl->allow($role->getName(), $component, ""); * } * } * @@ -68,9 +63,9 @@ * $acl->allow("Users", $component, $action); * } * } - *``` + * ``` */ -class Memory extends Adapter +class Memory extends \Phalcon\Acl\Adapter\AbstractAdapter { /** * Access @@ -86,11 +81,11 @@ class Memory extends Adapter */ protected $accessList; - /** - * Returns latest function used to acquire access - * - * @var mixed - */ + /** + * Returns latest function used to acquire access + * + * @var mixed + */ protected $activeFunction; /** @@ -98,7 +93,7 @@ class Memory extends Adapter * * @var int */ - protected $activeFunctionCustomArgumentsCount; + protected $activeFunctionCustomArgumentsCount = 0; /** * Returns latest key used to acquire access @@ -133,7 +128,7 @@ class Memory extends Adapter * * @var mixed */ - protected $noArgumentsDefaultAction = Acl::DENY; + protected $noArgumentsDefaultAction = Enum::DENY; /** * Roles @@ -157,6 +152,27 @@ class Memory extends Adapter protected $rolesNames; + /** + * Returns latest function used to acquire access + * + * @return mixed + */ + public function getActiveFunction() {} + + /** + * Returns number of additional arguments(excluding role and resource) for active function + * + * @return int + */ + public function getActiveFunctionCustomArgumentsCount(): int {} + + /** + * Returns latest key used to acquire access + * + * @return string|null + */ + public function getActiveKey(): ?string {} + /** * Phalcon\Acl\Adapter\Memory constructor */ @@ -195,20 +211,21 @@ public function __construct() {} * ] * ); * ``` - * @param $componentValue - * @param $accessList + * + * @param mixed $componentValue + * @param mixed $accessList * @return bool */ - public function addComponent($componentValue, $accessList) : bool {} + public function addComponent($componentValue, $accessList): bool {} /** * Adds access to components * - * @param $componentName - * @param $accessList + * @param string $componentName + * @param mixed $accessList * @return bool */ - public function addComponentAccess(string $componentName, $accessList) : bool {} + public function addComponentAccess(string $componentName, $accessList): bool {} /** * Do a role inherit from another existing role @@ -219,10 +236,10 @@ public function addComponentAccess(string $componentName, $accessList) : bool {} * ``` * * @param string $roleName - * @param $roleToInherits + * @param mixed $roleToInherits * @return bool */ - public function addInherit(string $roleName, $roleToInherits) : bool {} + public function addInherit(string $roleName, $roleToInherits): bool {} /** * Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role @@ -237,14 +254,14 @@ public function addInherit(string $roleName, $roleToInherits) : bool {} * $acl->addRole("administrator", ["consultant", "consultant2"]); * ``` * - * @param $role - * @param null $accessInherits + * @param mixed $role + * @param mixed $accessInherits * @return bool */ - public function addRole($role, $accessInherits = null) : bool {} + public function addRole($role, $accessInherits = null): bool {} /** - * Allow access to a role on a component. You can use `*` as wildcard + * Allow access to a role on a component. You can use `` as wildcard * * ```php * // Allow access to guests to search on customers @@ -254,20 +271,20 @@ public function addRole($role, $accessInherits = null) : bool {} * $acl->allow("guests", "customers", ["search", "create"]); * * // Allow access to any role to browse on products - * $acl->allow("*", "products", "browse"); + * $acl->allow("", "products", "browse"); * * // Allow access to any role to browse on any component - * $acl->allow("*", "*", "browse"); + * $acl->allow("", "", "browse"); * * @param string $roleName * @param string $componentName - * @param $access - * @param null $func + * @param mixed $access + * @param mixed $func */ - public function allow(string $roleName, string $componentName, $access, $func = null) : void {} + public function allow(string $roleName, string $componentName, $access, $func = null) {} /** - * Deny access to a role on a component. You can use `*` as wildcard + * Deny access to a role on a component. You can use `` as wildcard * * ```php * // Deny access to guests to search on customers @@ -277,45 +294,48 @@ public function allow(string $roleName, string $componentName, $access, $func = * $acl->deny("guests", "customers", ["search", "create"]); * * // Deny access to any role to browse on products - * $acl->deny("*", "products", "browse"); + * $acl->deny("", "products", "browse"); * * // Deny access to any role to browse on any component - * $acl->deny("*", "*", "browse"); + * $acl->deny("", "", "browse"); * ``` * * @param string $roleName * @param string $componentName - * @param $access - * @param null $func + * @param mixed $access + * @param mixed $func */ - public function deny(string $roleName, string $componentName, $access, $func = null) : void {} + public function deny(string $roleName, string $componentName, $access, $func = null) {} /** * Removes an access from a component + * * @param string $componentName - * @param $accessList + * @param mixed $accessList */ - public function dropComponentAccess(string $componentName, $accessList) : void {} + public function dropComponentAccess(string $componentName, $accessList) {} /** * Returns the default ACL access level for no arguments provided in * `isAllowed` action if a `func` (callable) exists for `accessKey` + * + * @return int */ - public function getNoArgumentsDefaultAction() : int {} + public function getNoArgumentsDefaultAction(): int {} /** * Return an array with every role registered in the list * - * @return RoleInterface[] + * @return array|\Phalcon\Acl\RoleInterface[] */ - public function getRoles() : array {} + public function getRoles(): array {} /** * Return an array with every component registered in the list * - * @return ComponentInterface[] + * @return array|\Phalcon\Acl\ComponentInterface[] */ - public function getComponents() : array {} + public function getComponents(): array {} /** * Check whether a role is allowed to access an action from a component @@ -325,15 +345,16 @@ public function getComponents() : array {} * $acl->isAllowed("andres", "Products", "create"); * * // Do guests have access to any component to edit? - * $acl->isAllowed("guests", "*", "edit"); + * $acl->isAllowed("guests", "", "edit"); * ``` - * @param $roleName - * @param $componentName - * @param $access - * @param array|null $parameters + * + * @param mixed $roleName + * @param mixed $componentName + * @param string $access + * @param array $parameters * @return bool */ - public function isAllowed($roleName, $componentName, $access, ?array $parameters = null) : bool {} + public function isAllowed($roleName, $componentName, string $access, array $parameters = null): bool {} /** * Check whether role exist in the roles list @@ -341,7 +362,7 @@ public function isAllowed($roleName, $componentName, $access, ?array $parameters * @param string $roleName * @return bool */ - public function isRole(string $roleName) : bool {} + public function isRole(string $roleName): bool {} /** * Check whether component exist in the components list @@ -349,14 +370,36 @@ public function isRole(string $roleName) : bool {} * @param string $componentName * @return bool */ - public function isComponent(string $componentName) : bool {} + public function isComponent(string $componentName): bool {} /** - * Sets the default access level (`Phalcon\Acl::ALLOW` or `Phalcon\Acl::DENY`) + * Sets the default access level (`Phalcon\Enum::ALLOW` or `Phalcon\Enum::DENY`) * for no arguments provided in isAllowed action if there exists func for * accessKey * * @param int $defaultAccess */ - public function setNoArgumentsDefaultAction(int $defaultAccess) : void {} + public function setNoArgumentsDefaultAction(int $defaultAccess) {} + + /** + * Checks if a role has access to a component + * + * @param string $roleName + * @param string $componentName + * @param mixed $access + * @param mixed $action + * @param mixed $func + */ + private function allowOrDeny(string $roleName, string $componentName, $access, $action, $func = null) {} + + /** + * Check whether a role is allowed to access an action from a component + * + * @param string $roleName + * @param string $componentName + * @param string $access + * @return string|bool + */ + private function canAccess(string $roleName, string $componentName, string $access) {} + } diff --git a/src/Phalcon/annotations/Annotation.php b/src/Phalcon/annotations/Annotation.php index 0819c6fd..09c42994 100644 --- a/src/Phalcon/annotations/Annotation.php +++ b/src/Phalcon/annotations/Annotation.php @@ -3,32 +3,30 @@ namespace Phalcon\Annotations; /** - * Phalcon\Annotations\Annotation - * * Represents a single annotation in an annotations collection */ class Annotation { /** - * Annotation Name + * Annotation Arguments * - * @var string + * @var array */ - protected $_name; + protected $arguments; /** - * Annotation Arguments + * Annotation ExprArguments * * @var string */ - protected $_arguments; + protected $exprArguments; /** - * Annotation ExprArguments + * Annotation Name * * @var string */ - protected $_exprArguments; + protected $name; /** @@ -39,71 +37,69 @@ class Annotation public function __construct(array $reflectionData) {} /** - * Returns the annotation's name + * Returns an argument in a specific position * - * @return string + * @param mixed $position */ - public function getName() {} + public function getArgument($position) {} /** - * Resolves an annotation expression + * Returns the expression arguments * - * @param array $expr - * @return mixed + * @return array */ - public function getExpression(array $expr) {} + public function getArguments(): array {} /** * Returns the expression arguments without resolving * * @return array */ - public function getExprArguments() {} + public function getExprArguments(): array {} /** - * Returns the expression arguments + * Resolves an annotation expression * - * @return array + * @param array $expr + * @return mixed */ - public function getArguments() {} + public function getExpression(array $expr) {} /** - * Returns the number of arguments that the annotation has + * Returns the annotation's name * - * @return int + * @return string */ - public function numberArguments() {} + public function getName(): string {} /** - * Returns an argument in a specific position + * Returns a named argument * - * @param int|string $position - * @return mixed + * @param string $name */ - public function getArgument($position) {} + public function getNamedArgument(string $name) {} /** - * Returns an argument in a specific position + * Returns a named parameter * - * @param int|string $position - * @return bool + * @param string $name + * @return mixed */ - public function hasArgument($position) {} + public function getNamedParameter(string $name) {} /** - * Returns a named argument + * Returns an argument in a specific position * - * @param string $name - * @return mixed + * @param mixed $position + * @return bool */ - public function getNamedArgument($name) {} + public function hasArgument($position): bool {} /** - * Returns a named parameter + * Returns the number of arguments that the annotation has * - * @param string $name - * @return mixed + * @return int */ - public function getNamedParameter($name) {} + public function numberArguments(): int {} } diff --git a/src/Phalcon/annotations/AnnotationsFactory.php b/src/Phalcon/annotations/AnnotationsFactory.php new file mode 100644 index 00000000..474b8c63 --- /dev/null +++ b/src/Phalcon/annotations/AnnotationsFactory.php @@ -0,0 +1,42 @@ + - * //Traverse annotations + * ```php + * // Traverse annotations * foreach ($classAnnotations as $annotation) { * echo "Name=", $annotation->getName(), PHP_EOL; * } * - * //Check if the annotations has a specific + * // Check if the annotations has a specific * var_dump($classAnnotations->has("Cacheable")); * - * //Get an specific annotation in the collection + * // Get an specific annotation in the collection * $annotation = $classAnnotations->get("Cacheable"); - * + * ``` */ class Collection implements \Iterator, \Countable { + /** + * @var array + */ + protected $annotations; - protected $_position = 0; - - - protected $_annotations; + /** + * @var int + */ + protected $position = 0; /** @@ -34,19 +37,14 @@ class Collection implements \Iterator, \Countable * * @param array $reflectionData */ - public function __construct($reflectionData = null) {} + public function __construct(array $reflectionData = array()) {} /** * Returns the number of annotations in the collection * * @return int */ - public function count() {} - - /** - * Rewinds the internal iterator - */ - public function rewind() {} + public function count(): int {} /** * Returns the current annotation in the iterator @@ -56,53 +54,58 @@ public function rewind() {} public function current() {} /** - * Returns the current position/key in the iterator + * Returns the first annotation that match a name * - * @return int - */ - public function key() {} - - /** - * Moves the internal iteration pointer to the next position + * @param string $name + * @return \Phalcon\Annotations\Annotation */ - public function next() {} + public function get(string $name): Annotation {} /** - * Check if the current annotation in the iterator is valid + * Returns all the annotations that match a name * - * @return bool + * @param string $name + * @return array|\Phalcon\Annotations\Annotation[] */ - public function valid() {} + public function getAll(string $name): array {} /** * Returns the internal annotations as an array * - * @return \Phalcon\Annotations\Annotation[] + * @return array|\Phalcon\Annotations\Annotation[] */ - public function getAnnotations() {} + public function getAnnotations(): array {} /** - * Returns the first annotation that match a name + * Check if an annotation exists in a collection * * @param string $name - * @return \Phalcon\Annotations\Annotation + * @return bool */ - public function get($name) {} + public function has(string $name): bool {} /** - * Returns all the annotations that match a name + * Returns the current position/key in the iterator * - * @param string $name - * @return \Phalcon\Annotations\Annotation[] + * @return int */ - public function getAll($name) {} + public function key(): int {} /** - * Check if an annotation exists in a collection + * Moves the internal iteration pointer to the next position + */ + public function next() {} + + /** + * Rewinds the internal iterator + */ + public function rewind() {} + + /** + * Check if the current annotation in the iterator is valid * - * @param string $name * @return bool */ - public function has($name) {} + public function valid(): bool {} } diff --git a/src/Phalcon/annotations/Exception.php b/src/Phalcon/annotations/Exception.php index 22e5decf..8864d544 100644 --- a/src/Phalcon/annotations/Exception.php +++ b/src/Phalcon/annotations/Exception.php @@ -3,11 +3,9 @@ namespace Phalcon\Annotations; /** - * Phalcon\Annotations\Exception - * * Class for exceptions thrown by Phalcon\Annotations */ -class Exception extends \Exception +class Exception extends \Phalcon\Exception { } diff --git a/src/Phalcon/annotations/Factory.php b/src/Phalcon/annotations/Factory.php deleted file mode 100644 index 63dd2a8a..00000000 --- a/src/Phalcon/annotations/Factory.php +++ /dev/null @@ -1,28 +0,0 @@ - - * use Phalcon\Annotations\Factory; - * - * $options = [ - * "prefix" => "annotations", - * "lifetime" => "3600", - * "adapter" => "apc", - * ]; - * $annotations = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - -} diff --git a/src/Phalcon/annotations/Reader.php b/src/Phalcon/annotations/Reader.php index 3208daf9..fdc95680 100644 --- a/src/Phalcon/annotations/Reader.php +++ b/src/Phalcon/annotations/Reader.php @@ -3,20 +3,18 @@ namespace Phalcon\Annotations; /** - * Phalcon\Annotations\Reader - * * Parses docblocks returning an array with the found annotations */ class Reader implements \Phalcon\Annotations\ReaderInterface { /** - * Reads annotations from the class dockblocks, its methods and/or properties + * Reads annotations from the class docblocks, its methods and/or properties * * @param string $className * @return array */ - public function parse($className) {} + public function parse(string $className): array {} /** * Parses a raw doc block returning the annotations found @@ -26,6 +24,6 @@ public function parse($className) {} * @param mixed $line * @return array */ - public static function parseDocBlock($docBlock, $file = null, $line = null) {} + public static function parseDocBlock(string $docBlock, $file = null, $line = null): array {} } diff --git a/src/Phalcon/annotations/ReaderInterface.php b/src/Phalcon/annotations/ReaderInterface.php index 1e6ce946..5ba4b965 100644 --- a/src/Phalcon/annotations/ReaderInterface.php +++ b/src/Phalcon/annotations/ReaderInterface.php @@ -3,29 +3,27 @@ namespace Phalcon\Annotations; /** - * Phalcon\Annotations\Reader - * * Parses docblocks returning an array with the found annotations */ interface ReaderInterface { /** - * Reads annotations from the class dockblocks, its methods and/or properties + * Reads annotations from the class docblocks, its methods and/or properties * * @param string $className * @return array */ - public function parse($className); + public function parse(string $className): array; /** - * Parses a raw doc block returning the annotations found + * Parses a raw docblock returning the annotations found * * @param string $docBlock * @param mixed $file * @param mixed $line * @return array */ - public static function parseDocBlock($docBlock, $file = null, $line = null); + public static function parseDocBlock(string $docBlock, $file = null, $line = null): array; } diff --git a/src/Phalcon/annotations/Reflection.php b/src/Phalcon/annotations/Reflection.php index 6bca75ff..97072543 100644 --- a/src/Phalcon/annotations/Reflection.php +++ b/src/Phalcon/annotations/Reflection.php @@ -3,11 +3,9 @@ namespace Phalcon\Annotations; /** - * Phalcon\Annotations\Reflection - * * Allows to manipulate the annotations reflection in an OO manner * - * + * ```php * use Phalcon\Annotations\Reader; * use Phalcon\Annotations\Reflection; * @@ -20,21 +18,23 @@ * * // Get the annotations in the class docblock * $classAnnotations = $reflection->getClassAnnotations(); - * + * ``` */ class Reflection { - protected $_reflectionData; - + protected $classAnnotations; - protected $_classAnnotations; + protected $methodAnnotations; - protected $_methodAnnotations; + protected $propertyAnnotations; - protected $_propertyAnnotations; + /** + * @var array + */ + protected $reflectionData; /** @@ -42,7 +42,7 @@ class Reflection * * @param array $reflectionData */ - public function __construct($reflectionData = null) {} + public function __construct(array $reflectionData = array()) {} /** * Returns the annotations found in the class docblock @@ -54,30 +54,23 @@ public function getClassAnnotations() {} /** * Returns the annotations found in the methods' docblocks * - * @return bool|\Phalcon\Annotations\Collection[] + * @return array|bool|\Phalcon\Annotations\Collection[] */ public function getMethodsAnnotations() {} /** * Returns the annotations found in the properties' docblocks * - * @return bool|\Phalcon\Annotations\Collection[] + * @return array|bool|\Phalcon\Annotations\Collection[] */ public function getPropertiesAnnotations() {} /** - * Returns the raw parsing intermediate definitions used to construct the reflection + * Returns the raw parsing intermediate definitions used to construct the + * reflection * * @return array */ - public function getReflectionData() {} - - /** - * Restores the state of a Phalcon\Annotations\Reflection variable export - * - * @param mixed $data - * @return Reflection - */ - public static function __set_state($data) {} + public function getReflectionData(): array {} } diff --git a/src/Phalcon/annotations/Adapter.php b/src/Phalcon/annotations/adapter/AbstractAdapter.php similarity index 63% rename from src/Phalcon/annotations/Adapter.php rename to src/Phalcon/annotations/adapter/AbstractAdapter.php index 2b9a8b55..e20924a3 100644 --- a/src/Phalcon/annotations/Adapter.php +++ b/src/Phalcon/annotations/adapter/AbstractAdapter.php @@ -1,42 +1,39 @@ - * use Phalcon\Annotations\Adapter\Apc; - * - * $annotations = new Apc(); - * - * - * @see \Phalcon\Annotations\Adapter\Apcu - * @deprecated - */ -class Apc extends \Phalcon\Annotations\Adapter -{ - - protected $_prefix = ''; - - - protected $_ttl = 172800; - - - /** - * Phalcon\Annotations\Adapter\Apc constructor - * - * @param array $options - */ - public function __construct($options = null) {} - - /** - * Reads parsed annotations from APC - * - * @param string $key - * @return bool|\Phalcon\Annotations\Reflection - */ - public function read($key) {} - - /** - * Writes parsed annotations to APC - * - * @param string $key - * @param \Phalcon\Annotations\Reflection $data - */ - public function write($key, \Phalcon\Annotations\Reflection $data) {} - -} diff --git a/src/Phalcon/annotations/adapter/Apcu.php b/src/Phalcon/annotations/adapter/Apcu.php index 0eabb8a8..3eedce01 100644 --- a/src/Phalcon/annotations/adapter/Apcu.php +++ b/src/Phalcon/annotations/adapter/Apcu.php @@ -3,23 +3,25 @@ namespace Phalcon\Annotations\Adapter; /** - * Phalcon\Annotations\Adapter\Apcu - * * Stores the parsed annotations in APCu. This adapter is suitable for production * - * + * ```php * use Phalcon\Annotations\Adapter\Apcu; * * $annotations = new Apcu(); - * + * ``` */ -class Apcu extends \Phalcon\Annotations\Adapter +class Apcu extends \Phalcon\Annotations\Adapter\AbstractAdapter { + /** + * @var string + */ + protected $prefix = ''; - protected $_prefix = ''; - - - protected $_ttl = 172800; + /** + * @var int + */ + protected $ttl = 172800; /** @@ -27,7 +29,7 @@ class Apcu extends \Phalcon\Annotations\Adapter * * @param array $options */ - public function __construct($options = null) {} + public function __construct(array $options = array()) {} /** * Reads parsed annotations from APCu @@ -35,14 +37,15 @@ public function __construct($options = null) {} * @param string $key * @return bool|\Phalcon\Annotations\Reflection */ - public function read($key) {} + public function read(string $key) {} /** * Writes parsed annotations to APCu * * @param string $key * @param \Phalcon\Annotations\Reflection $data + * @return bool */ - public function write($key, \Phalcon\Annotations\Reflection $data) {} + public function write(string $key, \Phalcon\Annotations\Reflection $data): bool {} } diff --git a/src/Phalcon/annotations/adapter/Memory.php b/src/Phalcon/annotations/adapter/Memory.php index 421aa079..dff5586e 100644 --- a/src/Phalcon/annotations/adapter/Memory.php +++ b/src/Phalcon/annotations/adapter/Memory.php @@ -3,18 +3,15 @@ namespace Phalcon\Annotations\Adapter; /** - * Phalcon\Annotations\Adapter\Memory - * - * Stores the parsed annotations in memory. This adapter is the suitable development/testing + * Stores the parsed annotations in memory. This adapter is the suitable + * development/testing */ -class Memory extends \Phalcon\Annotations\Adapter +class Memory extends \Phalcon\Annotations\Adapter\AbstractAdapter { /** - * Data - * * @var mixed */ - protected $_data; + protected $data; /** @@ -23,7 +20,7 @@ class Memory extends \Phalcon\Annotations\Adapter * @param string $key * @return bool|\Phalcon\Annotations\Reflection */ - public function read($key) {} + public function read(string $key) {} /** * Writes parsed annotations to memory @@ -31,6 +28,6 @@ public function read($key) {} * @param string $key * @param \Phalcon\Annotations\Reflection $data */ - public function write($key, \Phalcon\Annotations\Reflection $data) {} + public function write(string $key, \Phalcon\Annotations\Reflection $data) {} } diff --git a/src/Phalcon/annotations/adapter/Files.php b/src/Phalcon/annotations/adapter/Stream.php similarity index 55% rename from src/Phalcon/annotations/adapter/Files.php rename to src/Phalcon/annotations/adapter/Stream.php index fc5be66d..1ceda655 100644 --- a/src/Phalcon/annotations/adapter/Files.php +++ b/src/Phalcon/annotations/adapter/Stream.php @@ -3,32 +3,32 @@ namespace Phalcon\Annotations\Adapter; /** - * Phalcon\Annotations\Adapter\Files - * * Stores the parsed annotations in files. This adapter is suitable for production * - * - * use Phalcon\Annotations\Adapter\Files; + * ```php + * use Phalcon\Annotations\Adapter\Stream; * - * $annotations = new Files( + * $annotations = new Stream( * [ * "annotationsDir" => "app/cache/annotations/", * ] * ); - * + * ``` */ -class Files extends \Phalcon\Annotations\Adapter +class Stream extends \Phalcon\Annotations\Adapter\AbstractAdapter { - - protected $_annotationsDir = './'; + /** + * @var string + */ + protected $annotationsDir = './'; /** - * Phalcon\Annotations\Adapter\Files constructor + * Phalcon\Annotations\Adapter\Stream constructor * * @param array $options */ - public function __construct($options = null) {} + public function __construct(array $options = array()) {} /** * Reads parsed annotations from files @@ -36,7 +36,7 @@ public function __construct($options = null) {} * @param string $key * @return bool|int|\Phalcon\Annotations\Reflection */ - public function read($key) {} + public function read(string $key) {} /** * Writes parsed annotations to files @@ -44,6 +44,6 @@ public function read($key) {} * @param string $key * @param \Phalcon\Annotations\Reflection $data */ - public function write($key, \Phalcon\Annotations\Reflection $data) {} + public function write(string $key, \Phalcon\Annotations\Reflection $data) {} } diff --git a/src/Phalcon/annotations/adapter/Xcache.php b/src/Phalcon/annotations/adapter/Xcache.php deleted file mode 100644 index 504b2674..00000000 --- a/src/Phalcon/annotations/adapter/Xcache.php +++ /dev/null @@ -1,33 +0,0 @@ - - * $annotations = new \Phalcon\Annotations\Adapter\Xcache(); - * - */ -class Xcache extends \Phalcon\Annotations\Adapter -{ - - /** - * Reads parsed annotations from XCache - * - * @param string $key - * @return bool|\Phalcon\Annotations\Reflection - */ - public function read($key) {} - - /** - * Writes parsed annotations to XCache - * - * @param string $key - * @param \Phalcon\Annotations\Reflection $data - */ - public function write($key, \Phalcon\Annotations\Reflection $data) {} - -} diff --git a/src/Phalcon/Application.php b/src/Phalcon/application/AbstractApplication.php similarity index 58% rename from src/Phalcon/Application.php rename to src/Phalcon/application/AbstractApplication.php index 6b5b964a..b0376906 100644 --- a/src/Phalcon/Application.php +++ b/src/Phalcon/application/AbstractApplication.php @@ -1,91 +1,97 @@ + * ```php * $this->registerModules( * [ * "frontend" => [ - * "className" => "Multiple\\Frontend\\Module", + * "className" => \Multiple\Frontend\Module::class, * "path" => "../apps/frontend/Module.php", * ], * "backend" => [ - * "className" => "Multiple\\Backend\\Module", + * "className" => \Multiple\Backend\Module::class, * "path" => "../apps/backend/Module.php", * ], * ] * ); - * + * ``` * * @param array $modules * @param bool $merge * @return Application */ - public function registerModules(array $modules, $merge = false) {} - - /** - * Return the modules registered in the application - * - * @return array - */ - public function getModules() {} - - /** - * Gets the module definition registered in the application via module name - * - * @param string $name - * @return array|object - */ - public function getModule($name) {} + public function registerModules(array $modules, bool $merge = false): Application {} /** * Sets the module name to be used if the router doesn't return a valid module @@ -93,18 +99,14 @@ public function getModule($name) {} * @param string $defaultModule * @return Application */ - public function setDefaultModule($defaultModule) {} + public function setDefaultModule(string $defaultModule): Application {} /** - * Returns the default module name + * Sets the events manager * - * @return string - */ - public function getDefaultModule() {} - - /** - * Handles a request + * @param \Phalcon\Events\ManagerInterface $eventsManager + * @return Application */ - abstract public function handle(); + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager): Application {} } diff --git a/src/Phalcon/application/Exception.php b/src/Phalcon/application/Exception.php index f400d62a..9e2d5a57 100644 --- a/src/Phalcon/application/Exception.php +++ b/src/Phalcon/application/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Application; /** - * Phalcon\Application\Exception - * * Exceptions thrown in Phalcon\Application class will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/assets/Asset.php b/src/Phalcon/assets/Asset.php index 16acb66d..431db7dc 100644 --- a/src/Phalcon/assets/Asset.php +++ b/src/Phalcon/assets/Asset.php @@ -3,176 +3,247 @@ namespace Phalcon\Assets; /** - * Phalcon\Assets\Asset - * * Represents an asset asset * - * + * ```php * $asset = new \Phalcon\Assets\Asset("js", "javascripts/jquery.js"); - * + * ``` */ -class Asset implements AssetInterface +class Asset implements \Phalcon\Assets\AssetInterface { - /** - * @var array | null - */ - protected $attributes; - - /** - * @var bool - */ - protected $filter; - - /** - * @var bool - */ - protected $local; - - /** - * @var string - */ - protected $path; - - /** - * @var string - */ - protected $sourcePath; - - /** - * @var string - */ - protected $targetPath; - - /** - * @var string - */ - protected $targetUri; - - /** - * @var string - */ - protected $type; - - /** - * Phalcon\Assets\Asset constructor - */ - public function __construct(string $type, string $path, bool $local = true, bool $filter = true, array $attributes = []) - { - } - - /** - * Sets the asset's type - */ - public function setType(string $type) : AssetInterface - { - } - - /** - * Sets the asset's path - */ - public function setPath(string $path) : AssetInterface - { - } - - /** - * Sets if the asset is local or external - */ - public function setLocal(bool $local) : AssetInterface - { - } - - /** - * Sets if the asset must be filtered or not - */ - public function setFilter(bool $filter) : AssetInterface - { - } - - /** - * Sets extra HTML attributes - */ - public function setAttributes(array $attributes) : AssetInterface - { - } - - /** - * Sets a target uri for the generated HTML - */ - public function setTargetUri(string $targetUri) : AssetInterface - { - } - - /** - * Sets the asset's source path - */ - public function setSourcePath(string $sourcePath) : AssetInterface - { - } - - /** - * Sets the asset's target path - */ - public function setTargetPath(string $targetPath) : AssetInterface - { - } - - /** - * Returns the content of the asset as an string - * Optionally a base path where the asset is located can be set - */ - public function getContent(string $basePath = null) : string - { - } - - /** - * Returns the real target uri for the generated HTML - */ - public function getRealTargetUri() : string - { - } - - /** - * Returns the complete location where the asset is located - */ - public function getRealSourcePath(string $basePath = null) : string - { - } - - /** - * Returns the complete location where the asset must be written - */ - public function getRealTargetPath(string $basePath = null) : string - { - } - - /** - * Gets the asset's key. - */ - public function getAssetKey() : string - { - } - - /** - * Gets the asset's type. - */ - public function getType(): string - { - // TODO: Implement getType() method. - } - - /** - * Gets if the asset must be filtered or not. - */ - public function getFilter(): bool - { - // TODO: Implement getFilter() method. - } - - /** - * Gets extra HTML attributes. - */ - public function getAttributes(): array - { - // TODO: Implement getAttributes() method. - } + /** + * @var array | null + */ + protected $attributes; + + /** + * @var bool + */ + protected $autoVersion = false; + + /** + * @var bool + */ + protected $filter; + + /** + * @var bool + */ + protected $local; + + /** + * @var string + */ + protected $path; + + /** + * @var string + */ + protected $sourcePath; + + /** + * @var string + */ + protected $targetPath; + + /** + * @var string + */ + protected $targetUri; + + /** + * @var string + */ + protected $type; + + /** + * Version of resource + * + * @var string + */ + protected $version; + + + /** + * @return array|null + */ + public function getAttributes(): ?array {} + + /** + * @param bool $autoVersion + */ + public function setAutoVersion(bool $autoVersion) {} + + /** + * @return bool + */ + public function getFilter(): bool {} + + /** + * @return bool + */ + public function getLocal(): bool {} + + /** + * @return string + */ + public function getPath(): string {} + + /** + * @return string + */ + public function getSourcePath(): string {} + + /** + * @return string + */ + public function getTargetPath(): string {} + + /** + * @return string + */ + public function getTargetUri(): string {} + + /** + * @return string + */ + public function getType(): string {} + + /** + * Version of resource + * + * @return string + */ + public function getVersion(): string {} + + /** + * Version of resource + * + * @param string $version + */ + public function setVersion(string $version) {} + + /** + * Phalcon\Assets\Asset constructor + * + * @param string $type + * @param string $path + * @param bool $local + * @param bool $filter + * @param array $attributes + * @param string $version + * @param bool $autoVersion + */ + public function __construct(string $type, string $path, bool $local = true, bool $filter = true, array $attributes = array(), string $version = null, bool $autoVersion = false) {} + + /** + * Gets the asset's key. + * + * @return string + */ + public function getAssetKey(): string {} + + /** + * Returns the content of the asset as an string + * Optionally a base path where the asset is located can be set + * + * @param string $basePath + * @return string + */ + public function getContent(string $basePath = null): string {} + + /** + * Returns the complete location where the asset is located + * + * @param string $basePath + * @return string + */ + public function getRealSourcePath(string $basePath = null): string {} + + /** + * Returns the complete location where the asset must be written + * + * @param string $basePath + * @return string + */ + public function getRealTargetPath(string $basePath = null): string {} + + /** + * Returns the real target uri for the generated HTML + * + * @return string + */ + public function getRealTargetUri(): string {} + + /** + * Checks if resource is using auto version + * + * @return bool + */ + public function isAutoVersion(): bool {} + + /** + * Sets extra HTML attributes + * + * @param array $attributes + * @return AssetInterface + */ + public function setAttributes(array $attributes): AssetInterface {} + + /** + * Sets if the asset must be filtered or not + * + * @param bool $filter + * @return AssetInterface + */ + public function setFilter(bool $filter): AssetInterface {} + + /** + * Sets if the asset is local or external + * + * @param bool $local + * @return AssetInterface + */ + public function setLocal(bool $local): AssetInterface {} + + /** + * Sets the asset's source path + * + * @param string $sourcePath + * @return AssetInterface + */ + public function setSourcePath(string $sourcePath): AssetInterface {} + + /** + * Sets the asset's target path + * + * @param string $targetPath + * @return AssetInterface + */ + public function setTargetPath(string $targetPath): AssetInterface {} + + /** + * Sets a target uri for the generated HTML + * + * @param string $targetUri + * @return AssetInterface + */ + public function setTargetUri(string $targetUri): AssetInterface {} + + /** + * Sets the asset's type + * + * @param string $type + * @return AssetInterface + */ + public function setType(string $type): AssetInterface {} + + /** + * Sets the asset's path + * + * @param string $path + * @return AssetInterface + */ + public function setPath(string $path): AssetInterface {} + } diff --git a/src/Phalcon/assets/AssetInterface.php b/src/Phalcon/assets/AssetInterface.php new file mode 100644 index 00000000..c7bdf739 --- /dev/null +++ b/src/Phalcon/assets/AssetInterface.php @@ -0,0 +1,63 @@ + - * use Phalcon\Assets\Resource; - * use Phalcon\Assets\Collection; - * - * $collection = new Collection(); - * $resource = new Resource("js", "js/jquery.js"); - * $collection->add($resource); - * $collection->has($resource); // true - * + * Adds a filter to the collection * - * @param ResourceInterface $resource - * @return bool + * @param \Phalcon\Assets\FilterInterface $filter + * @return Collection */ - public function has(ResourceInterface $resource) {} + public function addFilter(\Phalcon\Assets\FilterInterface $filter): Collection {} /** - * Adds a CSS resource to the collection + * Adds an inline code to the collection * - * @param string $path - * @param mixed $local - * @param bool $filter - * @param mixed $attributes + * @param \Phalcon\Assets\Inline $code * @return Collection */ - public function addCss($path, $local = null, $filter = true, $attributes = null) {} + public function addInline(\Phalcon\Assets\Inline $code): Collection {} /** * Adds an inline CSS to the collection @@ -143,122 +218,138 @@ public function addCss($path, $local = null, $filter = true, $attributes = null) * @param mixed $attributes * @return Collection */ - public function addInlineCss($content, $filter = true, $attributes = null) {} + public function addInlineCss(string $content, bool $filter = true, $attributes = null): Collection {} /** - * Adds a javascript resource to the collection + * Adds an inline javascript to the collection * - * @param string $path - * @param boolean $local - * @param boolean $filter - * @param array $attributes + * @param string $content + * @param bool $filter + * @param mixed $attributes * @return Collection */ - public function addJs($path, $local = null, $filter = true, $attributes = null) {} + public function addInlineJs(string $content, bool $filter = true, $attributes = null): Collection {} /** - * Adds an inline javascript to the collection + * Adds a javascript asset to the collection * - * @param string $content + * @param string $path + * @param mixed $local * @param bool $filter - * @param mixed $attributes + * @param array $attributes + * @param string $version + * @param bool $autoVersion * @return Collection */ - public function addInlineJs($content, $filter = true, $attributes = null) {} + public function addJs(string $path, $local = null, bool $filter = true, $attributes = null, string $version = null, bool $autoVersion = false): Collection {} /** * Returns the number of elements in the form * * @return int */ - public function count() {} - - /** - * Rewinds the internal iterator - */ - public function rewind() {} + public function count(): int {} /** - * Returns the current resource in the iterator + * Returns the current asset in the iterator * - * @return \Phalcon\Assets\Resource + * @return \Phalcon\Assets\Asset */ - public function current() {} + public function current(): Asset {} /** - * Returns the current position/key in the iterator + * Returns the complete location where the joined/filtered collection must + * be written * - * @return int + * @param string $basePath + * @return string */ - public function key() {} + public function getRealTargetPath(string $basePath): string {} /** - * Moves the internal iteration pointer to the next position + * Checks this the asset is added to the collection. + * + * ```php + * use Phalcon\Assets\Asset; + * use Phalcon\Assets\Collection; + * + * $collection = new Collection(); + * + * $asset = new Asset("js", "js/jquery.js"); + * + * $collection->add($asset); + * $collection->has($asset); // true + * ``` + * + * @param AssetInterface $asset + * @return bool */ - public function next() {} + public function has(AssetInterface $asset): bool {} /** - * Check if the current element in the iterator is valid + * Checks if collection is using auto version * * @return bool */ - public function valid() {} + public function isAutoVersion(): bool {} /** - * Sets the target path of the file for the filtered/join output + * Sets if all filtered assets in the collection must be joined in a single + * result file * - * @param string $targetPath + * @param bool $join * @return Collection */ - public function setTargetPath($targetPath) {} + public function join(bool $join): Collection {} /** - * Sets a base source path for all the resources in this collection + * Returns the current position/key in the iterator * - * @param string $sourcePath - * @return Collection + * @return int */ - public function setSourcePath($sourcePath) {} + public function key(): int {} /** - * Sets a target uri for the generated HTML - * - * @param string $targetUri - * @return Collection + * Moves the internal iteration pointer to the next position + */ + public function next() {} + + /** + * Rewinds the internal iterator */ - public function setTargetUri($targetUri) {} + public function rewind() {} /** - * Sets a common prefix for all the resources + * Sets extra HTML attributes * - * @param string $prefix + * @param array $attributes * @return Collection */ - public function setPrefix($prefix) {} + public function setAttributes(array $attributes): Collection {} /** - * Sets if the collection uses local resources by default + * Sets an array of filters in the collection * - * @param bool $local + * @param array $filters * @return Collection */ - public function setLocal($local) {} + public function setFilters(array $filters): Collection {} /** - * Sets extra HTML attributes + * Sets if the collection uses local assets by default * - * @param array $attributes + * @param bool $local * @return Collection */ - public function setAttributes(array $attributes) {} + public function setLocal(bool $local): Collection {} /** - * Sets an array of filters in the collection + * Sets a common prefix for all the assets * - * @param array $filters + * @param string $prefix * @return Collection */ - public function setFilters(array $filters) {} + public function setPrefix(string $prefix): Collection {} /** * Sets the target local @@ -266,38 +357,45 @@ public function setFilters(array $filters) {} * @param bool $targetLocal * @return Collection */ - public function setTargetLocal($targetLocal) {} + public function setTargetLocal(bool $targetLocal): Collection {} /** - * Sets if all filtered resources in the collection must be joined in a single result file + * Sets the target path of the file for the filtered/join output * - * @param bool $join + * @param string $targetPath * @return Collection */ - public function join($join) {} + public function setTargetPath(string $targetPath): Collection {} /** - * Returns the complete location where the joined/filtered collection must be written + * Sets a target uri for the generated HTML * - * @param string $basePath - * @return string + * @param string $targetUri + * @return Collection */ - public function getRealTargetPath($basePath) {} + public function setTargetUri(string $targetUri): Collection {} /** - * Adds a filter to the collection + * Sets a base source path for all the assets in this collection * - * @param \Phalcon\Assets\FilterInterface $filter + * @param string $sourcePath * @return Collection */ - public function addFilter(\Phalcon\Assets\FilterInterface $filter) {} + public function setSourcePath(string $sourcePath): Collection {} + + /** + * Check if the current element in the iterator is valid + * + * @return bool + */ + public function valid(): bool {} /** - * Adds a resource or inline-code to the collection + * Adds a asset or inline-code to the collection * - * @param ResourceInterface $resource + * @param AssetInterface $asset * @return bool */ - protected final function addResource(ResourceInterface $resource) {} + final protected function addAsset(AssetInterface $asset): bool {} } diff --git a/src/Phalcon/assets/Exception.php b/src/Phalcon/assets/Exception.php index c3104d8d..49148351 100644 --- a/src/Phalcon/assets/Exception.php +++ b/src/Phalcon/assets/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Assets; /** - * Phalcon\Assets\Exception - * * Exceptions thrown in Phalcon\Assets will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/assets/FilterInterface.php b/src/Phalcon/assets/FilterInterface.php index 4d1d4911..e0ba66c2 100644 --- a/src/Phalcon/assets/FilterInterface.php +++ b/src/Phalcon/assets/FilterInterface.php @@ -3,8 +3,6 @@ namespace Phalcon\Assets; /** - * Phalcon\Assets\FilterInterface - * * Interface for custom Phalcon\Assets filters */ interface FilterInterface @@ -16,6 +14,6 @@ interface FilterInterface * @param string $content * @return string */ - public function filter($content); + public function filter(string $content): string; } diff --git a/src/Phalcon/assets/Inline.php b/src/Phalcon/assets/Inline.php index 15b0be65..de5d3bef 100644 --- a/src/Phalcon/assets/Inline.php +++ b/src/Phalcon/assets/Inline.php @@ -3,92 +3,94 @@ namespace Phalcon\Assets; /** - * Phalcon\Assets\Inline - * * Represents an inline asset * - * + * ```php * $inline = new \Phalcon\Assets\Inline("js", "alert('hello world');"); - * + * ``` */ -class Inline implements \Phalcon\Assets\ResourceInterface +class Inline implements \Phalcon\Assets\AssetInterface { /** - * @var string + * @var array | null */ - protected $_type; + protected $attributes; - - protected $_content; + /** + * @var string + */ + protected $content; /** * @var bool */ - protected $_filter; + protected $filter; + /** + * @var string + */ + protected $type; - protected $_attributes; + /** + * @return array|null + */ + public function getAttributes(): ?array {} /** * @return string */ - public function getType() {} - - - public function getContent() {} + public function getContent(): string {} /** * @return bool */ - public function getFilter() {} + public function getFilter(): bool {} /** - * Phalcon\Assets\Inline constructor - * - * @param string $type - * @param string $content - * @param boolean $filter - * @param array $attributes + * @return string */ - public function __construct($type, $content, $filter = true, $attributes = null) {} + public function getType(): string {} /** - * Sets the inline's type + * Phalcon\Assets\Inline constructor * * @param string $type - * @return ResourceInterface + * @param string $content + * @param bool $filter + * @param array $attributes */ - public function setType($type) {} + public function __construct(string $type, string $content, bool $filter = true, array $attributes = array()) {} /** - * Sets if the resource must be filtered or not + * Gets the asset's key. * - * @param bool $filter - * @return ResourceInterface + * @return string */ - public function setFilter($filter) {} + public function getAssetKey(): string {} /** * Sets extra HTML attributes * * @param array $attributes - * @return ResourceInterface + * @return AssetInterface */ - public function setAttributes(array $attributes) {} + public function setAttributes(array $attributes): AssetInterface {} /** - * returns extra HTML attributes + * Sets if the asset must be filtered or not * - * @return array|null + * @param bool $filter + * @return AssetInterface */ - public function getAttributes() {} + public function setFilter(bool $filter): AssetInterface {} /** - * Gets the resource's key. + * Sets the inline's type * - * @return string + * @param string $type + * @return AssetInterface */ - public function getResourceKey() {} + public function setType(string $type): AssetInterface {} } diff --git a/src/Phalcon/assets/Manager.php b/src/Phalcon/assets/Manager.php index d93e5abb..f34300b8 100644 --- a/src/Phalcon/assets/Manager.php +++ b/src/Phalcon/assets/Manager.php @@ -7,203 +7,217 @@ * * Manages collections of CSS/Javascript assets */ -class Manager +class Manager implements \Phalcon\Di\InjectionAwareInterface { + + protected $collections; + + /** + * @var DiInterface + */ + protected $container; + /** * Options configure * * @var array */ - protected $_options; + protected $options; - - protected $_collections; - - - protected $_implicitOutput = true; + /** + * @var bool + */ + protected $implicitOutput = true; /** - * Phalcon\Assets\Manager + * Phalcon\Assets\Manager constructor * * @param array $options */ - public function __construct($options = null) {} + public function __construct(array $options = array()) {} /** - * Sets the manager options + * Adds a raw asset to the manager * - * @param array $options + * ```php + * $assets->addAsset( + * new Phalcon\Assets\Asset("css", "css/style.css") + * ); + * ``` + * + * @param \Phalcon\Assets\Asset $asset * @return Manager */ - public function setOptions(array $options) {} + public function addAsset(\Phalcon\Assets\Asset $asset): Manager {} /** - * Returns the manager options + * Adds a asset by its type * - * @return array - */ - public function getOptions() {} - - /** - * Sets if the HTML generated must be directly printed or returned + * ```php + * $assets->addAssetByType( + * "css", + * new \Phalcon\Assets\Asset\Css("css/style.css") + * ); + * ``` * - * @param bool $implicitOutput + * @param string $type + * @param \Phalcon\Assets\Asset $asset * @return Manager */ - public function useImplicitOutput($implicitOutput) {} + public function addAssetByType(string $type, \Phalcon\Assets\Asset $asset): Manager {} /** - * Adds a Css resource to the 'css' collection + * Adds a Css asset to the 'css' collection * - * + * ```php * $assets->addCss("css/bootstrap.css"); * $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); - * + * ``` * * @param string $path * @param mixed $local - * @param mixed $filter + * @param bool $filter * @param mixed $attributes + * @param string $version + * @param bool $autoVersion * @return Manager */ - public function addCss($path, $local = true, $filter = true, $attributes = null) {} + public function addCss(string $path, $local = true, bool $filter = true, $attributes = null, string $version = null, bool $autoVersion = false): Manager {} /** - * Adds an inline Css to the 'css' collection + * Adds a raw inline code to the manager * - * @param string $content - * @param mixed $filter - * @param mixed $attributes + * @param Inline $code * @return Manager */ - public function addInlineCss($content, $filter = true, $attributes = null) {} + public function addInlineCode(Inline $code): Manager {} /** - * Adds a javascript resource to the 'js' collection - * - * - * $assets->addJs("scripts/jquery.js"); - * $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); - * + * Adds an inline code by its type * - * @param string $path - * @param mixed $local - * @param mixed $filter - * @param mixed $attributes + * @param string $type + * @param Inline $code * @return Manager */ - public function addJs($path, $local = true, $filter = true, $attributes = null) {} + public function addInlineCodeByType(string $type, Inline $code): Manager {} /** - * Adds an inline javascript to the 'js' collection + * Adds an inline Css to the 'css' collection * * @param string $content * @param mixed $filter * @param mixed $attributes * @return Manager */ - public function addInlineJs($content, $filter = true, $attributes = null) {} + public function addInlineCss(string $content, $filter = true, $attributes = null): Manager {} /** - * Adds a resource by its type - * - * - * $assets->addResourceByType("css", - * new \Phalcon\Assets\Resource\Css("css/style.css") - * ); - * + * Adds an inline javascript to the 'js' collection * - * @param string $type - * @param \Phalcon\Assets\Resource $resource + * @param string $content + * @param mixed $filter + * @param mixed $attributes * @return Manager */ - public function addResourceByType($type, \Phalcon\Assets\Resource $resource) {} + public function addInlineJs(string $content, $filter = true, $attributes = null): Manager {} /** - * Adds an inline code by its type + * Adds a javascript asset to the 'js' collection * - * @param string $type - * @param Inline $code + * ```php + * $assets->addJs("scripts/jquery.js"); + * $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); + * ``` + * + * @param string $path + * @param mixed $local + * @param bool $filter + * @param mixed $attributes + * @param string $version + * @param bool $autoVersion * @return Manager */ - public function addInlineCodeByType($type, Inline $code) {} + public function addJs(string $path, $local = true, bool $filter = true, $attributes = null, string $version = null, bool $autoVersion = false): Manager {} /** - * Adds a raw resource to the manager + * Creates/Returns a collection of assets * - * - * $assets->addResource( - * new Phalcon\Assets\Resource("css", "css/style.css") - * ); - * - * - * @param \Phalcon\Assets\Resource $resource - * @return Manager + * @param string $name + * @return \Phalcon\Assets\Collection */ - public function addResource(\Phalcon\Assets\Resource $resource) {} + public function collection(string $name): Collection {} /** - * Adds a raw inline code to the manager + * Creates/Returns a collection of assets by type * - * @param Inline $code - * @return Manager + * @param array $assets + * @param string $type + * @return array */ - public function addInlineCode(Inline $code) {} + public function collectionAssetsByType(array $assets, string $type): array {} /** - * Sets a collection in the Assets Manager + * Returns true or false if collection exists. * - * - * $assets->set("js", $collection); - * + * ```php + * if ($assets->exists("jsHeader")) { + * // \Phalcon\Assets\Collection + * $collection = $assets->get("jsHeader"); + * } + * ``` * * @param string $id - * @param \Phalcon\Assets\Collection $collection - * @return Manager + * @return bool */ - public function set($id, \Phalcon\Assets\Collection $collection) {} + public function exists(string $id): bool {} /** * Returns a collection by its id. * - * + * ```php * $scripts = $assets->get("js"); - * + * ``` * * @param string $id * @return \Phalcon\Assets\Collection */ - public function get($id) {} + public function get(string $id): Collection {} /** - * Returns the CSS collection of assets + * Returns existing collections in the manager * - * @return \Phalcon\Assets\Collection + * @return array|\Phalcon\Assets\Collection[] */ - public function getCss() {} + public function getCollections(): array {} /** * Returns the CSS collection of assets * * @return \Phalcon\Assets\Collection */ - public function getJs() {} + public function getCss(): Collection {} /** - * Creates/Returns a collection of resources + * Returns the internal dependency injector + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Returns the CSS collection of assets * - * @param string $name * @return \Phalcon\Assets\Collection */ - public function collection($name) {} + public function getJs(): Collection {} /** - * @param array $resources - * @param string $type + * Returns the manager options + * * @return array */ - public function collectionResourcesByType(array $resources, $type) {} + public function getOptions(): array {} /** * Traverses a collection calling the callback to generate its HTML @@ -213,7 +227,15 @@ public function collectionResourcesByType(array $resources, $type) {} * @param string $type * @return string|null */ - public function output(\Phalcon\Assets\Collection $collection, $callback, $type) {} + public function output(\Phalcon\Assets\Collection $collection, $callback, $type): ?string {} + + /** + * Prints the HTML for CSS assets + * + * @param string $collectionName + * @return string + */ + public function outputCss(string $collectionName = null): string {} /** * Traverses a collection and generate its HTML @@ -222,60 +244,75 @@ public function output(\Phalcon\Assets\Collection $collection, $callback, $type) * @param string $type * @return string */ - public function outputInline(\Phalcon\Assets\Collection $collection, $type) {} + public function outputInline(\Phalcon\Assets\Collection $collection, $type): string {} /** - * Prints the HTML for CSS resources + * Prints the HTML for inline CSS * * @param string $collectionName * @return string */ - public function outputCss($collectionName = null) {} + public function outputInlineCss(string $collectionName = null): string {} /** - * Prints the HTML for inline CSS + * Prints the HTML for inline JS * * @param string $collectionName * @return string */ - public function outputInlineCss($collectionName = null) {} + public function outputInlineJs(string $collectionName = null): string {} /** - * Prints the HTML for JS resources + * Prints the HTML for JS assets * * @param string $collectionName * @return string */ - public function outputJs($collectionName = null) {} + public function outputJs(string $collectionName = null): string {} /** - * Prints the HTML for inline JS + * Sets a collection in the Assets Manager * - * @param string $collectionName - * @return string + * ```php + * $assets->set("js", $collection); + * ``` + * + * @param string $id + * @param \Phalcon\Assets\Collection $collection + * @return Manager */ - public function outputInlineJs($collectionName = null) {} + public function set(string $id, \Phalcon\Assets\Collection $collection): Manager {} /** - * Returns existing collections in the manager + * Sets the dependency injector * - * @return \Phalcon\Assets\Collection[] + * @param \Phalcon\Di\DiInterface $container */ - public function getCollections() {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Returns true or false if collection exists. + * Sets the manager options * - * - * if ($assets->exists("jsHeader")) { - * // \Phalcon\Assets\Collection - * $collection = $assets->get("jsHeader"); - * } - * + * @param array $options + * @return Manager + */ + public function setOptions(array $options): Manager {} + + /** + * Sets if the HTML generated must be directly printed or returned * - * @param string $id - * @return bool + * @param bool $implicitOutput + * @return Manager + */ + public function useImplicitOutput(bool $implicitOutput): Manager {} + + /** + * Returns the prefixed path + * + * @param \Phalcon\Assets\Collection $collection + * @param string $path + * @return string */ - public function exists($id) {} + private function getPrefixedPath(\Phalcon\Assets\Collection $collection, string $path): string {} } diff --git a/src/Phalcon/assets/Resource.php b/src/Phalcon/assets/Resource.php deleted file mode 100644 index 82a0acf8..00000000 --- a/src/Phalcon/assets/Resource.php +++ /dev/null @@ -1,199 +0,0 @@ - - * $resource = new \Phalcon\Assets\Resource("js", "javascripts/jquery.js"); - * - */ -class Resource implements \Phalcon\Assets\ResourceInterface -{ - /** - * @var string - */ - protected $_type; - - /** - * @var string - */ - protected $_path; - - /** - * @var boolean - */ - protected $_local; - - /** - * @var bool - */ - protected $_filter; - - /** - * @var array | null - */ - protected $_attributes; - - - protected $_sourcePath; - - - protected $_targetPath; - - - protected $_targetUri; - - - /** - * @return string - */ - public function getType() {} - - /** - * @return string - */ - public function getPath() {} - - /** - * @return boolean - */ - public function getLocal() {} - - /** - * @return bool - */ - public function getFilter() {} - - /** - * @return array|null - */ - public function getAttributes() {} - - - public function getSourcePath() {} - - - public function getTargetPath() {} - - - public function getTargetUri() {} - - /** - * Phalcon\Assets\Resource constructor - * - * @param string $type - * @param string $path - * @param boolean $local - * @param boolean $filter - * @param array $attributes - */ - public function __construct($type, $path, $local = true, $filter = true, $attributes = null) {} - - /** - * Sets the resource's type - * - * @param string $type - * @return ResourceInterface - */ - public function setType($type) {} - - /** - * Sets the resource's path - * - * @param string $path - * @return Resource - */ - public function setPath($path) {} - - /** - * Sets if the resource is local or external - * - * @param bool $local - * @return Resource - */ - public function setLocal($local) {} - - /** - * Sets if the resource must be filtered or not - * - * @param bool $filter - * @return ResourceInterface - */ - public function setFilter($filter) {} - - /** - * Sets extra HTML attributes - * - * @param array $attributes - * @return ResourceInterface - */ - public function setAttributes(array $attributes) {} - - /** - * Sets a target uri for the generated HTML - * - * @param string $targetUri - * @return Resource - */ - public function setTargetUri($targetUri) {} - - /** - * Sets the resource's source path - * - * @param string $sourcePath - * @return Resource - */ - public function setSourcePath($sourcePath) {} - - /** - * Sets the resource's target path - * - * @param string $targetPath - * @return Resource - */ - public function setTargetPath($targetPath) {} - - /** - * Returns the content of the resource as an string - * Optionally a base path where the resource is located can be set - * - * @param string $basePath - * @return string - */ - public function getContent($basePath = null) {} - - /** - * Returns the real target uri for the generated HTML - * - * @return string - */ - public function getRealTargetUri() {} - - /** - * Returns the complete location where the resource is located - * - * @param string $basePath - * @return string - */ - public function getRealSourcePath($basePath = null) {} - - /** - * Returns the complete location where the resource must be written - * - * @param string $basePath - * @return string - */ - public function getRealTargetPath($basePath = null) {} - - /** - * Gets the resource's key. - * - * @return string - */ - public function getResourceKey() {} - -} diff --git a/src/Phalcon/assets/ResourceInterface.php b/src/Phalcon/assets/ResourceInterface.php deleted file mode 100644 index c34ad4b7..00000000 --- a/src/Phalcon/assets/ResourceInterface.php +++ /dev/null @@ -1,65 +0,0 @@ - - * use Phalcon\Cache\Frontend\Data as DataFrontend; - * use Phalcon\Cache\Multiple; - * use Phalcon\Cache\Backend\Apc as ApcCache; - * use Phalcon\Cache\Backend\Memcache as MemcacheCache; - * use Phalcon\Cache\Backend\File as FileCache; - * - * $ultraFastFrontend = new DataFrontend( - * [ - * "lifetime" => 3600, - * ] - * ); - * - * $fastFrontend = new DataFrontend( - * [ - * "lifetime" => 86400, - * ] - * ); - * - * $slowFrontend = new DataFrontend( - * [ - * "lifetime" => 604800, - * ] - * ); - * - * //Backends are registered from the fastest to the slower - * $cache = new Multiple( - * [ - * new ApcCache( - * $ultraFastFrontend, - * [ - * "prefix" => "cache", - * ] - * ), - * new MemcacheCache( - * $fastFrontend, - * [ - * "prefix" => "cache", - * "host" => "localhost", - * "port" => "11211", - * ] - * ), - * new FileCache( - * $slowFrontend, - * [ - * "prefix" => "cache", - * "cacheDir" => "../app/cache/", - * ] - * ), - * ] - * ); - * - * //Save, saves in every backend - * $cache->save("my-key", $data); - * - */ -class Multiple -{ - - protected $_backends; - - - /** - * Phalcon\Cache\Multiple constructor - * - * @param Phalcon\Cache\BackendInterface[] backends - * @param mixed $backends - */ - public function __construct($backends = null) {} - - /** - * Adds a backend - * - * @param \Phalcon\Cache\BackendInterface $backend - * @return Multiple - */ - public function push(\Phalcon\Cache\BackendInterface $backend) {} - - /** - * Returns a cached content reading the internal backends - * - * @param string|int $keyName - * @param int $lifetime - * @return mixed - */ - public function get($keyName, $lifetime = null) {} - - /** - * Starts every backend - * - * @param string|int $keyName - * @param int $lifetime - */ - public function start($keyName, $lifetime = null) {} - - /** - * Stores cached content into all backends and stops the frontend - * - * @param string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = null) {} - - /** - * Deletes a value from each backend - * - * @param string|int $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Checks if cache exists in at least one backend - * - * @param string|int $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Flush all backend(s) - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/adapter/AdapterInterface.php b/src/Phalcon/cache/adapter/AdapterInterface.php new file mode 100644 index 00000000..0acab0d8 --- /dev/null +++ b/src/Phalcon/cache/adapter/AdapterInterface.php @@ -0,0 +1,11 @@ + - * use Phalcon\Cache\Backend\Apc; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * $cache = new Apc( - * $frontCache, - * [ - * "prefix" => "app-data", - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - * - * @see \Phalcon\Cache\Backend\Apcu - * @deprecated - */ -class Apc extends \Phalcon\Cache\Backend -{ - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the APC backend and stops the frontend - * - * @param string|int $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Increment of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Deletes a value from the cache by its key - * - * @param string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it hasn't expired - * - * @param string|int $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Immediately invalidates all existing items. - * - * - * use Phalcon\Cache\Backend\Apc; - * - * $cache = new Apc($frontCache, ["prefix" => "app-data"]); - * - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // 'my-data' and all other used keys are deleted - * $cache->flush(); - * - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Apcu.php b/src/Phalcon/cache/backend/Apcu.php deleted file mode 100644 index 66151d00..00000000 --- a/src/Phalcon/cache/backend/Apcu.php +++ /dev/null @@ -1,126 +0,0 @@ - - * use Phalcon\Cache\Backend\Apcu; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * $cache = new Apcu( - * $frontCache, - * [ - * "prefix" => "app-data", - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Apcu extends \Phalcon\Cache\Backend -{ - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the APCu backend and stops the frontend - * - * @param string|int $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Increment of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Deletes a value from the cache by its key - * - * @param string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it hasn't expired - * - * @param string|int $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Immediately invalidates all existing items. - * - * - * use Phalcon\Cache\Backend\Apcu; - * - * $cache = new Apcu($frontCache, ["prefix" => "app-data"]); - * - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // 'my-data' and all other used keys are deleted - * $cache->flush(); - * - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Factory.php b/src/Phalcon/cache/backend/Factory.php deleted file mode 100644 index ffb31f6b..00000000 --- a/src/Phalcon/cache/backend/Factory.php +++ /dev/null @@ -1,35 +0,0 @@ - - * use Phalcon\Cache\Backend\Factory; - * use Phalcon\Cache\Frontend\Data; - * - * $options = [ - * "prefix" => "app-data", - * "frontend" => new Data(), - * "adapter" => "apc", - * ]; - * $backendCache = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return \Phalcon\Cache\BackendInterface - */ - public static function load($config) {} - - /** - * @param string $namespace - * @param mixed $config - */ - protected static function loadClass($namespace, $config) {} - -} diff --git a/src/Phalcon/cache/backend/File.php b/src/Phalcon/cache/backend/File.php deleted file mode 100644 index 06837215..00000000 --- a/src/Phalcon/cache/backend/File.php +++ /dev/null @@ -1,152 +0,0 @@ - - * use Phalcon\Cache\Backend\File; - * use Phalcon\Cache\Frontend\Output as FrontOutput; - * - * // Cache the file for 2 days - * $frontendOptions = [ - * "lifetime" => 172800, - * ]; - * - * // Create an output cache - * $frontCache = FrontOutput($frontOptions); - * - * // Set the cache directory - * $backendOptions = [ - * "cacheDir" => "../app/cache/", - * ]; - * - * // Create the File backend - * $cache = new File($frontCache, $backendOptions); - * - * $content = $cache->start("my-cache"); - * - * if ($content === null) { - * echo "

", time(), "

"; - * - * $cache->save(); - * } else { - * echo $content; - * } - * - */ -class File extends \Phalcon\Cache\Backend -{ - /** - * Default to false for backwards compatibility - * - * @var boolean - */ - private $_useSafeKey = false; - - - /** - * Phalcon\Cache\Backend\File constructor - * - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param array $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, array $options) {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string|int $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Increment of a given key, by number $value - * - * @param string|int $keyName - * @param int $value - * @return int|null - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of a given key, by number $value - * - * @param string|int $keyName - * @param int $value - * @return int|null - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - - /** - * Return a file-system safe identifier for a given key - * - * @param mixed $key - * @return string - */ - public function getKey($key) {} - - /** - * Set whether to use the safekey or not - * - * @param bool $useSafeKey - * @return File - */ - public function useSafeKey($useSafeKey) {} - -} diff --git a/src/Phalcon/cache/backend/Libmemcached.php b/src/Phalcon/cache/backend/Libmemcached.php deleted file mode 100644 index 89bb77a9..00000000 --- a/src/Phalcon/cache/backend/Libmemcached.php +++ /dev/null @@ -1,162 +0,0 @@ - - * use Phalcon\Cache\Backend\Libmemcached; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the Cache setting memcached connection options - * $cache = new Libmemcached( - * $frontCache, - * [ - * "servers" => [ - * [ - * "host" => "127.0.0.1", - * "port" => 11211, - * "weight" => 1, - * ], - * ], - * "client" => [ - * \Memcached::OPT_HASH => \Memcached::HASH_MD5, - * \Memcached::OPT_PREFIX_KEY => "prefix.", - * ], - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Libmemcached extends \Phalcon\Cache\Backend -{ - - protected $_memcache = null; - - - /** - * Phalcon\Cache\Backend\Memcache constructor - * - * @param Phalcon\Cache\FrontendInterface frontend - * @param array options - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param mixed $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, $options = null) {} - - /** - * Create internal connection to memcached - */ - public function _connect() {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return boolean - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Increment of given $keyName by $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of $keyName by given $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. - * All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. - * - * - * $cache = new \Phalcon\Cache\Backend\Libmemcached( - * $frontCache, - * [ - * "statsKey" => "_PHCM", - * ] - * ); - * - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // 'my-data' and all other used keys are deleted - * $cache->flush(); - * - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Memcache.php b/src/Phalcon/cache/backend/Memcache.php deleted file mode 100644 index 446c7c63..00000000 --- a/src/Phalcon/cache/backend/Memcache.php +++ /dev/null @@ -1,148 +0,0 @@ - - * use Phalcon\Cache\Backend\Memcache; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the Cache setting memcached connection options - * $cache = new Memcache( - * $frontCache, - * [ - * "host" => "localhost", - * "port" => 11211, - * "persistent" => false, - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Memcache extends \Phalcon\Cache\Backend -{ - - protected $_memcache = null; - - - /** - * Phalcon\Cache\Backend\Memcache constructor - * - * @param Phalcon\Cache\FrontendInterface frontend - * @param array options - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param mixed $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, $options = null) {} - - /** - * Create internal connection to memcached - */ - public function _connect() {} - - /** - * Add servers to memcache pool - * - * @param string $host - * @param int $port - * @param bool $persistent - * @return bool - */ - public function addServers($host, $port, $persistent = false) {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return boolean - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Increment of given $keyName by $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of $keyName by given $value - * - * @param string $keyName - * @param int $value - * @return int|bool - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Memory.php b/src/Phalcon/cache/backend/Memory.php deleted file mode 100644 index f4ca7853..00000000 --- a/src/Phalcon/cache/backend/Memory.php +++ /dev/null @@ -1,123 +0,0 @@ - - * use Phalcon\Cache\Backend\Memory; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data - * $frontCache = new FrontData(); - * - * $cache = new Memory($frontCache); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Memory extends \Phalcon\Cache\Backend implements \Serializable -{ - - protected $_data; - - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the backend and stops the frontend - * - * @param string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it hasn't expired - * - * @param string|int $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Increment of given $keyName by $value - * - * @param string $keyName - * @param int $value - * @return int|null - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of $keyName by given $value - * - * @param string $keyName - * @param int $value - * @return int|null - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - - /** - * Required for interface \Serializable - * - * @return string - */ - public function serialize() {} - - /** - * Required for interface \Serializable - * - * @param mixed $data - */ - public function unserialize($data) {} - -} diff --git a/src/Phalcon/cache/backend/Mongo.php b/src/Phalcon/cache/backend/Mongo.php deleted file mode 100644 index fe92cb29..00000000 --- a/src/Phalcon/cache/backend/Mongo.php +++ /dev/null @@ -1,146 +0,0 @@ - - * use Phalcon\Cache\Backend\Mongo; - * use Phalcon\Cache\Frontend\Base64; - * - * // Cache data for 2 days - * $frontCache = new Base64( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create a MongoDB cache - * $cache = new Mongo( - * $frontCache, - * [ - * "server" => "mongodb://localhost", - * "db" => "caches", - * "collection" => "images", - * ] - * ); - * - * // Cache arbitrary data - * $cache->save( - * "my-data", - * file_get_contents("some-image.jpg") - * ); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Mongo extends \Phalcon\Cache\Backend -{ - - protected $_collection = null; - - - /** - * Phalcon\Cache\Backend\Mongo constructor - * - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param array $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, $options = null) {} - - /** - * Returns a MongoDb collection based on the backend parameters - * - * @return MongoCollection - */ - protected final function _getCollection() {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * gc - * - * @return collection->remove(...) - */ - public function gc() {} - - /** - * Increment of a given key by $value - * - * @param int|string $keyName - * @param int $value - * @return int|null - */ - public function increment($keyName, $value = 1) {} - - /** - * Decrement of a given key by $value - * - * @param int|string $keyName - * @param int $value - * @return int|null - */ - public function decrement($keyName, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Redis.php b/src/Phalcon/cache/backend/Redis.php deleted file mode 100644 index 731df280..00000000 --- a/src/Phalcon/cache/backend/Redis.php +++ /dev/null @@ -1,147 +0,0 @@ - - * use Phalcon\Cache\Backend\Redis; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the Cache setting redis connection options - * $cache = new Redis( - * $frontCache, - * [ - * "host" => "localhost", - * "port" => 6379, - * "auth" => "foobared", - * "persistent" => false, - * "index" => 0, - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Redis extends \Phalcon\Cache\Backend -{ - - protected $_redis = null; - - - /** - * Phalcon\Cache\Backend\Redis constructor - * - * @param Phalcon\Cache\FrontendInterface frontend - * @param array options - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param mixed $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, $options = null) {} - - /** - * Create internal connection to redis - */ - public function _connect() {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * - * $cache->save("my-key", $data); - * - * // Save data termlessly - * $cache->save("my-key", $data, -1); - * - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return bool - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Increment of given $keyName by $value - * - * @param string $keyName - * @param int $value - * @return int - */ - public function increment($keyName = null, $value = 1) {} - - /** - * Decrement of $keyName by given $value - * - * @param string $keyName - * @param int $value - * @return int - */ - public function decrement($keyName = null, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/backend/Xcache.php b/src/Phalcon/cache/backend/Xcache.php deleted file mode 100644 index f1ef2761..00000000 --- a/src/Phalcon/cache/backend/Xcache.php +++ /dev/null @@ -1,123 +0,0 @@ - - * use Phalcon\Cache\Backend\Xcache; - * use Phalcon\Cache\Frontend\Data as FrontData; - * - * // Cache data for 2 days - * $frontCache = new FrontData( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * $cache = new Xcache( - * $frontCache, - * [ - * "prefix" => "app-data", - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Xcache extends \Phalcon\Cache\Backend -{ - - /** - * Phalcon\Cache\Backend\Xcache constructor - * - * @param \Phalcon\Cache\FrontendInterface $frontend - * @param array $options - */ - public function __construct(\Phalcon\Cache\FrontendInterface $frontend, $options = null) {} - - /** - * Returns a cached content - * - * @param string $keyName - * @param int $lifetime - * @return mixed|null - */ - public function get($keyName, $lifetime = null) {} - - /** - * Stores cached content into the file backend and stops the frontend - * - * @param int|string $keyName - * @param string $content - * @param int $lifetime - * @param boolean $stopBuffer - * @return bool - */ - public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) {} - - /** - * Deletes a value from the cache by its key - * - * @param int|string $keyName - * @return boolean - */ - public function delete($keyName) {} - - /** - * Query the existing cached keys. - * - * - * $cache->save("users-ids", [1, 2, 3]); - * $cache->save("projects-ids", [4, 5, 6]); - * - * var_dump($cache->queryKeys("users")); // ["users-ids"] - * - * - * @param string $prefix - * @return array - */ - public function queryKeys($prefix = null) {} - - /** - * Checks if cache exists and it isn't expired - * - * @param string $keyName - * @param int $lifetime - * @return bool - */ - public function exists($keyName = null, $lifetime = null) {} - - /** - * Atomic increment of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int - */ - public function increment($keyName, $value = 1) {} - - /** - * Atomic decrement of a given key, by number $value - * - * @param string $keyName - * @param int $value - * @return int - */ - public function decrement($keyName, $value = 1) {} - - /** - * Immediately invalidates all existing items. - * - * @return bool - */ - public function flush() {} - -} diff --git a/src/Phalcon/cache/exception/Exception.php b/src/Phalcon/cache/exception/Exception.php new file mode 100644 index 00000000..cd483e0a --- /dev/null +++ b/src/Phalcon/cache/exception/Exception.php @@ -0,0 +1,11 @@ + - * 172800, - * ] - * ); - * - * //Create a MongoDB cache - * $cache = new \Phalcon\Cache\Backend\Mongo( - * $frontCache, - * [ - * "server" => "mongodb://localhost", - * "db" => "caches", - * "collection" => "images", - * ] - * ); - * - * $cacheKey = "some-image.jpg.cache"; - * - * // Try to get cached image - * $image = $cache->get($cacheKey); - * - * if ($image === null) { - * // Store the image in the cache - * $cache->save( - * $cacheKey, - * file_get_contents("tmp-dir/some-image.jpg") - * ); - * } - * - * header("Content-Type: image/jpeg"); - * - * echo $image; - * - */ -class Base64 implements \Phalcon\Cache\FrontendInterface -{ - - protected $_frontendOptions; - - - /** - * Phalcon\Cache\Frontend\Base64 constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Actually, does nothing in this adapter - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - * @return string - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/Data.php b/src/Phalcon/cache/frontend/Data.php deleted file mode 100644 index 4ea0ef05..00000000 --- a/src/Phalcon/cache/frontend/Data.php +++ /dev/null @@ -1,114 +0,0 @@ - - * use Phalcon\Cache\Backend\File; - * use Phalcon\Cache\Frontend\Data; - * - * // Cache the files for 2 days using a Data frontend - * $frontCache = new Data( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the component that will cache "Data" to a 'File' backend - * // Set the cache file directory - important to keep the '/' at the end of - * // of the value for the folder - * $cache = new File( - * $frontCache, - * [ - * "cacheDir" => "../app/cache/", - * ] - * ); - * - * $cacheKey = "robots_order_id.cache"; - * - * // Try to get cached records - * $robots = $cache->get($cacheKey); - * - * if ($robots === null) { - * // $robots is null due to cache expiration or data does not exist - * // Make the database call and populate the variable - * $robots = Robots::find( - * [ - * "order" => "id", - * ] - * ); - * - * // Store it in the cache - * $cache->save($cacheKey, $robots); - * } - * - * // Use $robots :) - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } - * - */ -class Data implements \Phalcon\Cache\FrontendInterface -{ - - protected $_frontendOptions; - - - /** - * Phalcon\Cache\Frontend\Data constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Actually, does nothing - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/Factory.php b/src/Phalcon/cache/frontend/Factory.php deleted file mode 100644 index 61fd18e3..00000000 --- a/src/Phalcon/cache/frontend/Factory.php +++ /dev/null @@ -1,33 +0,0 @@ - - * use Phalcon\Cache\Frontend\Factory; - * - * $options = [ - * "lifetime" => 172800, - * "adapter" => "data", - * ]; - * $frontendCache = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return \Phalcon\Cache\FrontendInterface - */ - public static function load($config) {} - - /** - * @param string $namespace - * @param mixed $config - */ - protected static function loadClass($namespace, $config) {} - -} diff --git a/src/Phalcon/cache/frontend/Igbinary.php b/src/Phalcon/cache/frontend/Igbinary.php deleted file mode 100644 index 3b366e4f..00000000 --- a/src/Phalcon/cache/frontend/Igbinary.php +++ /dev/null @@ -1,109 +0,0 @@ - - * // Cache the files for 2 days using Igbinary frontend - * $frontCache = new \Phalcon\Cache\Frontend\Igbinary( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the component that will cache "Igbinary" to a "File" backend - * // Set the cache file directory - important to keep the "/" at the end of - * // of the value for the folder - * $cache = new \Phalcon\Cache\Backend\File( - * $frontCache, - * [ - * "cacheDir" => "../app/cache/", - * ] - * ); - * - * $cacheKey = "robots_order_id.cache"; - * - * // Try to get cached records - * $robots = $cache->get($cacheKey); - * - * if ($robots === null) { - * // $robots is null due to cache expiration or data do not exist - * // Make the database call and populate the variable - * $robots = Robots::find( - * [ - * "order" => "id", - * ] - * ); - * - * // Store it in the cache - * $cache->save($cacheKey, $robots); - * } - * - * // Use $robots :) - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } - * - */ -class Igbinary extends \Phalcon\Cache\Frontend\Data implements \Phalcon\Cache\FrontendInterface -{ - - /** - * Phalcon\Cache\Frontend\Data constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Actually, does nothing - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - * @return string - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/Json.php b/src/Phalcon/cache/frontend/Json.php deleted file mode 100644 index 05bf6fc5..00000000 --- a/src/Phalcon/cache/frontend/Json.php +++ /dev/null @@ -1,102 +0,0 @@ - - * 172800, - * ] - * ); - * - * // Create the Cache setting memcached connection options - * $cache = new \Phalcon\Cache\Backend\Memcache( - * $frontCache, - * [ - * "host" => "localhost", - * "port" => 11211, - * "persistent" => false, - * ] - * ); - * - * // Cache arbitrary data - * $cache->save("my-data", [1, 2, 3, 4, 5]); - * - * // Get data - * $data = $cache->get("my-data"); - * - */ -class Json implements \Phalcon\Cache\FrontendInterface -{ - - protected $_frontendOptions; - - - /** - * Phalcon\Cache\Frontend\Base64 constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Actually, does nothing - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - * @return string - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/Msgpack.php b/src/Phalcon/cache/frontend/Msgpack.php deleted file mode 100644 index 66bb57fe..00000000 --- a/src/Phalcon/cache/frontend/Msgpack.php +++ /dev/null @@ -1,115 +0,0 @@ - - * use Phalcon\Cache\Backend\File; - * use Phalcon\Cache\Frontend\Msgpack; - * - * // Cache the files for 2 days using Msgpack frontend - * $frontCache = new Msgpack( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the component that will cache "Msgpack" to a "File" backend - * // Set the cache file directory - important to keep the "/" at the end of - * // of the value for the folder - * $cache = new File( - * $frontCache, - * [ - * "cacheDir" => "../app/cache/", - * ] - * ); - * - * $cacheKey = "robots_order_id.cache"; - * - * // Try to get cached records - * $robots = $cache->get($cacheKey); - * - * if ($robots === null) { - * // $robots is null due to cache expiration or data do not exist - * // Make the database call and populate the variable - * $robots = Robots::find( - * [ - * "order" => "id", - * ] - * ); - * - * // Store it in the cache - * $cache->save($cacheKey, $robots); - * } - * - * // Use $robots - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } - * - */ -class Msgpack extends \Phalcon\Cache\Frontend\Data implements \Phalcon\Cache\FrontendInterface -{ - - /** - * Phalcon\Cache\Frontend\Msgpack constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Actually, does nothing - */ - public function start() {} - - /** - * Returns output cached content - * - * @return null - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - * @return string - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/None.php b/src/Phalcon/cache/frontend/None.php deleted file mode 100644 index acce1cd2..00000000 --- a/src/Phalcon/cache/frontend/None.php +++ /dev/null @@ -1,98 +0,0 @@ - - * "localhost", - * "port" => "11211", - * ] - * ); - * - * $cacheKey = "robots_order_id.cache"; - * - * // This Frontend always return the data as it's returned by the backend - * $robots = $cache->get($cacheKey); - * - * if ($robots === null) { - * // This cache doesn't perform any expiration checking, so the data is always expired - * // Make the database call and populate the variable - * $robots = Robots::find( - * [ - * "order" => "id", - * ] - * ); - * - * $cache->save($cacheKey, $robots); - * } - * - * // Use $robots :) - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } - * - */ -class None implements \Phalcon\Cache\FrontendInterface -{ - - /** - * Returns cache lifetime, always one second expiring content - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output, always false - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Prepare data to be stored - * - * @param mixed $data - */ - public function beforeStore($data) {} - - /** - * Prepares data to be retrieved to user - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cache/frontend/Output.php b/src/Phalcon/cache/frontend/Output.php deleted file mode 100644 index eddcb223..00000000 --- a/src/Phalcon/cache/frontend/Output.php +++ /dev/null @@ -1,120 +0,0 @@ - - * use Phalcon\Tag; - * use Phalcon\Cache\Backend\File; - * use Phalcon\Cache\Frontend\Output; - * - * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output( - * [ - * "lifetime" => 172800, - * ] - * ); - * - * // Create the component that will cache from the "Output" to a "File" backend - * // Set the cache file directory - it's important to keep the "/" at the end of - * // the value for the folder - * $cache = new File( - * $frontCache, - * [ - * "cacheDir" => "../app/cache/", - * ] - * ); - * - * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start("my-cache.html"); - * - * // If $content is null then the content will be generated for the cache - * if (null === $content) { - * // Print date and time - * echo date("r"); - * - * // Generate a link to the sign-up action - * echo Tag::linkTo( - * [ - * "user/signup", - * "Sign Up", - * "class" => "signup-button", - * ] - * ); - * - * // Store the output into the cache file - * $cache->save(); - * } else { - * // Echo the cached output - * echo $content; - * } - * - */ -class Output implements \Phalcon\Cache\FrontendInterface -{ - - protected $_buffering = false; - - - protected $_frontendOptions; - - - /** - * Phalcon\Cache\Frontend\Output constructor - * - * @param array $frontendOptions - */ - public function __construct($frontendOptions = null) {} - - /** - * Returns the cache lifetime - * - * @return int - */ - public function getLifetime() {} - - /** - * Check whether if frontend is buffering output - * - * @return bool - */ - public function isBuffering() {} - - /** - * Starts output frontend. Currently, does nothing - */ - public function start() {} - - /** - * Returns output cached content - * - * @return string - */ - public function getContent() {} - - /** - * Stops output frontend - */ - public function stop() {} - - /** - * Serializes data before storing them - * - * @param mixed $data - * @return string - */ - public function beforeStore($data) {} - - /** - * Unserializes data after retrieval - * - * @param mixed $data - * @return mixed - */ - public function afterRetrieve($data) {} - -} diff --git a/src/Phalcon/cli/Console.php b/src/Phalcon/cli/Console.php index 01123b6d..2da7a60c 100644 --- a/src/Phalcon/cli/Console.php +++ b/src/Phalcon/cli/Console.php @@ -3,37 +3,20 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\Console - * * This component allows to create CLI applications using Phalcon */ -class Console extends \Phalcon\Application +class Console extends \Phalcon\Application\AbstractApplication { - - protected $_arguments = array(); - - - protected $_options = array(); - + /** + * @var array + */ + protected $arguments = array(); /** - * Merge modules with the existing ones - * - * - * $application->addModules( - * [ - * "admin" => [ - * "className" => "Multiple\\Admin\\Module", - * "path" => "../apps/admin/Module.php", - * ], - * ] - * ); - * - * - * @param array $modules - * @deprecated + * @var array */ - public function addModules(array $modules) {} + protected $options = array(); + /** * Handle the whole command-line tasks @@ -50,6 +33,6 @@ public function handle(array $arguments = null) {} * @param bool $shift * @return Console */ - public function setArgument(array $arguments = null, $str = true, $shift = true) {} + public function setArgument(array $arguments = null, bool $str = true, bool $shift = true): Console {} } diff --git a/src/Phalcon/cli/Dispatcher.php b/src/Phalcon/cli/Dispatcher.php index 28f105ea..3771ce22 100644 --- a/src/Phalcon/cli/Dispatcher.php +++ b/src/Phalcon/cli/Dispatcher.php @@ -3,18 +3,18 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\Dispatcher + * Dispatching is the process of taking the command-line arguments, extracting + * the module name, task name, action name, and optional parameters contained in + * it, and then instantiating a task and calling an action on it. * - * Dispatching is the process of taking the command-line arguments, extracting the module name, - * task name, action name, and optional parameters contained in it, and then - * instantiating a task and calling an action on it. - * - * + * ```php * use Phalcon\Di; * use Phalcon\Cli\Dispatcher; * * $di = new Di(); + * * $dispatcher = new Dispatcher(); + * * $dispatcher->setDi($di); * * $dispatcher->setTaskName("posts"); @@ -22,79 +22,100 @@ * $dispatcher->setParams([]); * * $handle = $dispatcher->dispatch(); - * + * ``` */ -class Dispatcher extends \Phalcon\Dispatcher implements \Phalcon\Cli\DispatcherInterface +class Dispatcher extends \Phalcon\Dispatcher\AbstractDispatcher implements \Phalcon\Cli\DispatcherInterface { + /** + * @var string + */ + protected $defaultHandler = 'main'; - protected $_handlerSuffix = 'Task'; - - - protected $_defaultHandler = 'main'; - + /** + * @var string + */ + protected $defaultAction = 'main'; - protected $_defaultAction = 'main'; + /** + * @var string + */ + protected $handlerSuffix = 'Task'; + /** + * @var array + */ + protected $options = array(); - protected $_options = array(); + /** + * Calls the action method. + * + * @param mixed $handler + * @param string $actionMethod + * @param array $params + * @return mixed + */ + public function callActionMethod($handler, string $actionMethod, array $params = array()) {} /** - * Sets the default task suffix + * Returns the active task in the dispatcher * - * @param string $taskSuffix + * @return TaskInterface */ - public function setTaskSuffix($taskSuffix) {} + public function getActiveTask(): TaskInterface {} /** - * Sets the default task name + * Returns the latest dispatched controller * - * @param string $taskName + * @return TaskInterface */ - public function setDefaultTask($taskName) {} + public function getLastTask(): TaskInterface {} /** - * Sets the task name to be dispatched + * Gets an option by its name or numeric index * - * @param string $taskName + * @param mixed $option + * @param string|array $filters + * @param mixed $defaultValue + * @return mixed */ - public function setTaskName($taskName) {} + public function getOption($option, $filters = null, $defaultValue = null) {} /** - * Gets last dispatched task name + * Get dispatched options * - * @return string + * @return array */ - public function getTaskName() {} + public function getOptions(): array {} /** - * Throws an internal exception + * Gets last dispatched task name * - * @param string $message - * @param int $exceptionCode + * @return string */ - protected function _throwDispatchException($message, $exceptionCode = 0) {} + public function getTaskName(): string {} /** - * Handles a user exception + * Gets the default task suffix * - * @param \Exception $exception + * @return string */ - protected function _handleException(\Exception $exception) {} + public function getTaskSuffix(): string {} /** - * Returns the latest dispatched controller + * Check if an option exists * - * @return TaskInterface + * @param mixed $option + * @return bool */ - public function getLastTask() {} + public function hasOption($option): bool {} /** - * Returns the active task in the dispatcher + * Sets the default task name * - * @return TaskInterface + * @param string $taskName */ - public function getActiveTask() {} + public function setDefaultTask(string $taskName) {} /** * Set the options to be dispatched @@ -104,38 +125,32 @@ public function getActiveTask() {} public function setOptions(array $options) {} /** - * Get dispatched options + * Sets the task name to be dispatched * - * @return array + * @param string $taskName */ - public function getOptions() {} + public function setTaskName(string $taskName) {} /** - * Gets an option by its name or numeric index + * Sets the default task suffix * - * @param mixed $option - * @param string|array $filters - * @param mixed $defaultValue - * @return mixed + * @param string $taskSuffix */ - public function getOption($option, $filters = null, $defaultValue = null) {} + public function setTaskSuffix(string $taskSuffix) {} /** - * Check if an option exists + * Handles a user exception * - * @param mixed $option - * @return bool + * @param \Exception $exception */ - public function hasOption($option) {} + protected function handleException(\Exception $exception) {} /** - * Calls the action method. + * Throws an internal exception * - * @param mixed $handler - * @param string $actionMethod - * @param array $params - * @return mixed + * @param string $message + * @param int $exceptionCode */ - public function callActionMethod($handler, $actionMethod, array $params = array()) {} + protected function throwDispatchException(string $message, int $exceptionCode = 0) {} } diff --git a/src/Phalcon/cli/DispatcherInterface.php b/src/Phalcon/cli/DispatcherInterface.php index 99a31ecc..eed77c38 100644 --- a/src/Phalcon/cli/DispatcherInterface.php +++ b/src/Phalcon/cli/DispatcherInterface.php @@ -3,53 +3,72 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\DispatcherInterface - * * Interface for Phalcon\Cli\Dispatcher */ -interface DispatcherInterface extends \Phalcon\DispatcherInterface +interface DispatcherInterface extends \Phalcon\Dispatcher\DispatcherInterface { /** - * Sets the default task suffix + * Returns the active task in the dispatcher * - * @param string $taskSuffix + * @return TaskInterface */ - public function setTaskSuffix($taskSuffix); + public function getActiveTask(): TaskInterface; /** - * Sets the default task name + * Returns the latest dispatched controller * - * @param string $taskName + * @return TaskInterface */ - public function setDefaultTask($taskName); + public function getLastTask(): TaskInterface; /** - * Sets the task name to be dispatched + * Get dispatched options * - * @param string $taskName + * @return array */ - public function setTaskName($taskName); + public function getOptions(): array; /** * Gets last dispatched task name * * @return string */ - public function getTaskName(); + public function getTaskName(): string; /** - * Returns the latest dispatched controller + * Gets default task suffix * - * @return TaskInterface + * @return string */ - public function getLastTask(); + public function getTaskSuffix(): string; /** - * Returns the active task in the dispatcher + * Sets the default task name * - * @return TaskInterface + * @param string $taskName + */ + public function setDefaultTask(string $taskName); + + /** + * Set the options to be dispatched + * + * @param array $options + */ + public function setOptions(array $options); + + /** + * Sets the task name to be dispatched + * + * @param string $taskName + */ + public function setTaskName(string $taskName); + + /** + * Sets the default task suffix + * + * @param string $taskSuffix */ - public function getActiveTask(); + public function setTaskSuffix(string $taskSuffix); } diff --git a/src/Phalcon/cli/Router.php b/src/Phalcon/cli/Router.php index 09c0cf0c..541e64b1 100644 --- a/src/Phalcon/cli/Router.php +++ b/src/Phalcon/cli/Router.php @@ -3,14 +3,12 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\Router + * Phalcon\Cli\Router is the standard framework router. Routing is the process + * of taking a command-line arguments and decomposing it into parameters to + * determine which module, task, and action of that task should receive the + * request. * - *

Phalcon\Cli\Router is the standard framework router. Routing is the - * process of taking a command-line arguments and - * decomposing it into parameters to determine which module, task, and - * action of that task should receive the request

- * - * + * ```php * $router = new \Phalcon\Cli\Router(); * * $router->handle( @@ -22,48 +20,52 @@ * ); * * echo $router->getTaskName(); - * + * ``` */ class Router implements \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; - + protected $action; - protected $_module; + protected $container; - protected $_task; + protected $defaultAction = null; - protected $_action; + protected $defaultModule = null; - protected $_params = array(); - + /** + * @var array + */ + protected $defaultParams = array(); - protected $_defaultModule = null; + protected $defaultTask = null; - protected $_defaultTask = null; + protected $matchedRoute; - protected $_defaultAction = null; + protected $matches; - protected $_defaultParams = array(); + protected $module; - protected $_routes; + /** + * @var array + */ + protected $params = array(); - protected $_matchedRoute; + protected $routes; - protected $_matches; + protected $task; - protected $_wasMatched = false; + protected $wasMatched = false; /** @@ -71,151 +73,152 @@ class Router implements \Phalcon\Di\InjectionAwareInterface * * @param bool $defaultRoutes */ - public function __construct($defaultRoutes = true) {} + public function __construct(bool $defaultRoutes = true) {} /** - * Sets the dependency injector + * Adds a route to the router + * + * ```php + * $router->add("/about", "About::main"); + * ``` * - * @param \Phalcon\DiInterface $dependencyInjector + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function add(string $pattern, $paths = null): RouteInterface {} /** - * Returns the internal dependency injector + * Returns processed action name * - * @return \Phalcon\DiInterface + * @return string */ - public function getDI() {} + public function getActionName(): string {} /** - * Sets the name of the default module + * Returns the internal dependency injector * - * @param string $moduleName + * @return \Phalcon\Di\DiInterface */ - public function setDefaultModule($moduleName) {} + public function getDI(): DiInterface {} /** - * Sets the default controller name + * Returns the route that matches the handled URI * - * @param string $taskName + * @return RouteInterface */ - public function setDefaultTask($taskName) {} + public function getMatchedRoute(): RouteInterface {} /** - * Sets the default action name + * Returns the sub expressions in the regular expression matched * - * @param string $actionName + * @return array */ - public function setDefaultAction($actionName) {} + public function getMatches(): array {} /** - * Sets an array of default paths. If a route is missing a path the router will use the defined here - * This method must not be used to set a 404 route - * - * - * $router->setDefaults( - * [ - * "module" => "common", - * "action" => "index", - * ] - * ); - * + * Returns processed module name * - * @param array $defaults - * @return Router + * @return string */ - public function setDefaults(array $defaults) {} + public function getModuleName(): string {} /** - * Handles routing information received from command-line arguments + * Returns processed extra params * - * @param array $arguments + * @return array */ - public function handle($arguments = null) {} + public function getParams(): array {} /** - * Adds a route to the router - * - * - * $router->add("/about", "About::main"); - * + * Returns a route object by its id * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @param int $id + * @return bool|RouteInterface */ - public function add($pattern, $paths = null) {} + public function getRouteById($id) {} /** - * Returns processed module name + * Returns a route object by its name * - * @return string + * @param string $name + * @return bool|RouteInterface */ - public function getModuleName() {} + public function getRouteByName(string $name) {} /** - * Returns processed task name + * Returns all the routes defined in the router * - * @return string + * @return array|\Phalcon\Cli\Router\Route[] */ - public function getTaskName() {} + public function getRoutes(): array {} /** - * Returns processed action name + * Returns processed task name * * @return string */ - public function getActionName() {} + public function getTaskName(): string {} /** - * Returns processed extra params + * Handles routing information received from command-line arguments * - * @return array + * @param array $arguments */ - public function getParams() {} + public function handle($arguments = null) {} /** - * Returns the route that matches the handled URI + * Sets the default action name * - * @return RouteInterface + * @param string $actionName */ - public function getMatchedRoute() {} + public function setDefaultAction(string $actionName) {} /** - * Returns the sub expressions in the regular expression matched + * Sets the name of the default module * - * @return array + * @param string $moduleName */ - public function getMatches() {} + public function setDefaultModule(string $moduleName) {} /** - * Checks if the router matches any of the defined routes + * Sets an array of default paths. If a route is missing a path the router + * will use the defined here. This method must not be used to set a 404 + * route * - * @return bool + * ```php + * $router->setDefaults( + * [ + * "module" => "common", + * "action" => "index", + * ] + * ); + * ``` + * + * @param array $defaults + * @return Router */ - public function wasMatched() {} + public function setDefaults(array $defaults): Router {} /** - * Returns all the routes defined in the router + * Sets the default controller name * - * @return \Phalcon\Cli\Router\Route[] + * @param string $taskName */ - public function getRoutes() {} + public function setDefaultTask(string $taskName) {} /** - * Returns a route object by its id + * Sets the dependency injector * - * @param int $id - * @return bool|RouteInterface + * @param \Phalcon\Di\DiInterface $container */ - public function getRouteById($id) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Returns a route object by its name + * Checks if the router matches any of the defined routes * - * @param string $name - * @return bool|RouteInterface + * @return bool */ - public function getRouteByName($name) {} + public function wasMatched(): bool {} } diff --git a/src/Phalcon/cli/RouterInterface.php b/src/Phalcon/cli/RouterInterface.php index 1d28c053..7f3d4abe 100644 --- a/src/Phalcon/cli/RouterInterface.php +++ b/src/Phalcon/cli/RouterInterface.php @@ -3,127 +3,125 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\RouterInterface - * * Interface for Phalcon\Cli\Router */ interface RouterInterface { /** - * Sets the name of the default module + * Adds a route to the router on any HTTP method * - * @param string $moduleName + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Cli\Router\RouteInterface */ - public function setDefaultModule($moduleName); + public function add(string $pattern, $paths = null): RouteInterface; /** - * Sets the default task name + * Returns processed action name * - * @param string $taskName + * @return string */ - public function setDefaultTask($taskName); + public function getActionName(): string; /** - * Sets the default action name + * Returns the route that matches the handled URI * - * @param string $actionName + * @return \Phalcon\Cli\Router\RouteInterface */ - public function setDefaultAction($actionName); + public function getMatchedRoute(): RouteInterface; /** - * Sets an array of default paths + * Return the sub expressions in the regular expression matched * - * @param array $defaults + * @return array */ - public function setDefaults(array $defaults); + public function getMatches(): array; /** - * Handles routing information received from the rewrite engine + * Returns processed module name * - * @param array $arguments + * @return string */ - public function handle($arguments = null); + public function getModuleName(): string; /** - * Adds a route to the router on any HTTP method + * Returns processed extra params * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Cli\Router\RouteInterface + * @return array */ - public function add($pattern, $paths = null); + public function getParams(): array; /** - * Returns processed module name + * Returns a route object by its id * - * @return string + * @param mixed $id + * @return \Phalcon\Cli\Router\RouteInterface */ - public function getModuleName(); + public function getRouteById($id): RouteInterface; /** - * Returns processed task name + * Returns a route object by its name * - * @return string + * @param string $name + * @return \Phalcon\Cli\Router\RouteInterface */ - public function getTaskName(); + public function getRouteByName(string $name): RouteInterface; /** - * Returns processed action name + * Return all the routes defined in the router * - * @return string + * @return array|\Phalcon\Cli\Router\RouteInterface[] */ - public function getActionName(); + public function getRoutes(): array; /** - * Returns processed extra params + * Returns processed task name * - * @return array + * @return string */ - public function getParams(); + public function getTaskName(): string; /** - * Returns the route that matches the handled URI + * Handles routing information received from the rewrite engine * - * @return \Phalcon\Cli\Router\RouteInterface + * @param array $arguments */ - public function getMatchedRoute(); + public function handle($arguments = null); /** - * Return the sub expressions in the regular expression matched + * Sets the default action name * - * @return array + * @param string $actionName */ - public function getMatches(); + public function setDefaultAction(string $actionName); /** - * Check if the router matches any of the defined routes + * Sets the name of the default module * - * @return bool + * @param string $moduleName */ - public function wasMatched(); + public function setDefaultModule(string $moduleName); /** - * Return all the routes defined in the router + * Sets an array of default paths * - * @return \Phalcon\Cli\Router\RouteInterface[] + * @param array $defaults */ - public function getRoutes(); + public function setDefaults(array $defaults); /** - * Returns a route object by its id + * Sets the default task name * - * @param mixed $id - * @return \Phalcon\Cli\Router\RouteInterface + * @param string $taskName */ - public function getRouteById($id); + public function setDefaultTask(string $taskName); /** - * Returns a route object by its name + * Check if the router matches any of the defined routes * - * @param string $name - * @return \Phalcon\Cli\Router\RouteInterface + * @return bool */ - public function getRouteByName($name); + public function wasMatched(): bool; } diff --git a/src/Phalcon/cli/Task.php b/src/Phalcon/cli/Task.php index 038a6603..41ba3342 100644 --- a/src/Phalcon/cli/Task.php +++ b/src/Phalcon/cli/Task.php @@ -3,14 +3,14 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\Task + * Every command-line task should extend this class that encapsulates all the + * task functionality * - * Every command-line task should extend this class that encapsulates all the task functionality + * A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, + * or anything that you want. The Task class should at least have a "mainAction" + * method. * - * A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. - * The Task class should at least have a "mainAction" method - * - * + * ```php * class HelloTask extends \Phalcon\Cli\Task * { * // This action will be executed by default @@ -24,7 +24,7 @@ * * } * } - * + * ``` */ class Task extends \Phalcon\Di\Injectable implements \Phalcon\Cli\TaskInterface { @@ -32,6 +32,6 @@ class Task extends \Phalcon\Di\Injectable implements \Phalcon\Cli\TaskInterface /** * Phalcon\Cli\Task constructor */ - public final function __construct() {} + final public function __construct() {} } diff --git a/src/Phalcon/cli/TaskInterface.php b/src/Phalcon/cli/TaskInterface.php index 2b561c82..9ceb7d69 100644 --- a/src/Phalcon/cli/TaskInterface.php +++ b/src/Phalcon/cli/TaskInterface.php @@ -3,8 +3,6 @@ namespace Phalcon\Cli; /** - * Phalcon\Cli\TaskInterface - * * Interface for task handlers */ interface TaskInterface diff --git a/src/Phalcon/cli/console/Exception.php b/src/Phalcon/cli/console/Exception.php index 602a4879..09649fa2 100644 --- a/src/Phalcon/cli/console/Exception.php +++ b/src/Phalcon/cli/console/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Cli\Console; /** - * Phalcon\Cli\Console\Exception - * * Exceptions thrown in Phalcon\Cli\Console will use this class */ class Exception extends \Phalcon\Application\Exception diff --git a/src/Phalcon/cli/dispatcher/Exception.php b/src/Phalcon/cli/dispatcher/Exception.php index 416f26a6..d03f5450 100644 --- a/src/Phalcon/cli/dispatcher/Exception.php +++ b/src/Phalcon/cli/dispatcher/Exception.php @@ -3,11 +3,9 @@ namespace Phalcon\Cli\Dispatcher; /** - * Phalcon\Cli\Dispatcher\Exception - * * Exceptions thrown in Phalcon\Cli\Dispatcher will use this class */ -class Exception extends \Phalcon\Exception +class Exception extends \Phalcon\Dispatcher\Exception { } diff --git a/src/Phalcon/cli/router/Exception.php b/src/Phalcon/cli/router/Exception.php index 6b6d0485..06f5a678 100644 --- a/src/Phalcon/cli/router/Exception.php +++ b/src/Phalcon/cli/router/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Cli\Router; /** - * Phalcon\Cli\Router\Exception - * * Exceptions thrown in Phalcon\Cli\Router will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/cli/router/Route.php b/src/Phalcon/cli/router/Route.php index 5b5e8ca6..5e0e0997 100644 --- a/src/Phalcon/cli/router/Route.php +++ b/src/Phalcon/cli/router/Route.php @@ -3,8 +3,6 @@ namespace Phalcon\Cli\Router; /** - * Phalcon\Cli\Router\Route - * * This class represents every route added to the router */ class Route @@ -13,159 +11,166 @@ class Route const DEFAULT_DELIMITER = ' '; - protected $_pattern; + protected $beforeMatch; - protected $_compiledPattern; + protected $compiledPattern; - protected $_paths; + protected $converters; - protected $_converters; + protected $delimiter; - protected $_id; + static protected $delimiterPath = self::DEFAULT_DELIMITER; - protected $_name; + protected $description; - protected $_beforeMatch; + protected $id; - protected $_delimiter; + protected $name; - static protected $_uniqueId; + protected $paths; - static protected $_delimiterPath; + protected $pattern; + + + static protected $uniqueId = 0; /** - * Phalcon\Cli\Router\Route constructor - * * @param string $pattern - * @param array $paths + * @param array|string $paths */ - public function __construct($pattern, $paths = null) {} + public function __construct(string $pattern, $paths = null) {} /** - * Replaces placeholders from pattern returning a valid PCRE regular expression + * Sets a callback that is called if the route is matched. + * The developer can implement any arbitrary conditions here + * If the callback returns false the route is treated as not matched * - * @param string $pattern - * @return string + * @param callback $callback + * @return RouteInterface */ - public function compilePattern($pattern) {} + public function beforeMatch($callback): RouteInterface {} /** - * Extracts parameters from a string + * Replaces placeholders from pattern returning a valid PCRE regular + * expression * * @param string $pattern - * @return array|boolean + * @return string */ - public function extractNamedParams($pattern) {} + public function compilePattern(string $pattern): string {} /** - * Reconfigure the route adding a new pattern and a set of paths + * Adds a converter to perform an additional transformation for certain + * parameter * - * @param string $pattern - * @param array $paths + * @param string $name + * @param callable $converter + * @return RouteInterface */ - public function reConfigure($pattern, $paths = null) {} + public function convert(string $name, $converter): RouteInterface {} /** - * Returns the route's name + * Set the routing delimiter * - * @return string + * @param string $delimiter */ - public function getName() {} + public static function delimiter(string $delimiter = null) {} /** - * Sets the route's name + * Extracts parameters from a string * - * - * $router->add( - * "/about", - * [ - * "controller" => "about", - * ] - * )->setName("about"); - * + * @param string $pattern + * @return array|bool + */ + public function extractNamedParams(string $pattern) {} + + /** + * Returns the 'before match' callback if any * - * @param string $name - * @return Route + * @return mixed */ - public function setName($name) {} + public function getBeforeMatch() {} /** - * Sets a callback that is called if the route is matched. - * The developer can implement any arbitrary conditions here - * If the callback returns false the route is treated as not matched + * Returns the route's compiled pattern * - * @param callback $callback - * @return Route + * @return string */ - public function beforeMatch($callback) {} + public function getCompiledPattern(): string {} /** - * Returns the 'before match' callback if any + * Returns the router converter * - * @return mixed + * @return array */ - public function getBeforeMatch() {} + public function getConverters(): array {} /** - * Returns the route's id + * Get routing delimiter * * @return string */ - public function getRouteId() {} + public static function getDelimiter(): string {} /** - * Returns the route's pattern + * Returns the route's description * * @return string */ - public function getPattern() {} + public function getDescription(): string {} /** - * Returns the route's compiled pattern + * Returns the route's name * * @return string */ - public function getCompiledPattern() {} + public function getName(): string {} /** * Returns the paths * * @return array */ - public function getPaths() {} + public function getPaths(): array {} + + /** + * Returns the route's pattern + * + * @return string + */ + public function getPattern(): string {} /** * Returns the paths using positions as keys and names as values * * @return array */ - public function getReversedPaths() {} + public function getReversedPaths(): array {} /** - * Adds a converter to perform an additional transformation for certain parameter + * Returns the route's id * - * @param string $name - * @param callable $converter - * @return Route + * @return string */ - public function convert($name, $converter) {} + public function getRouteId(): string {} /** - * Returns the router converter + * Reconfigure the route adding a new pattern and a set of paths * - * @return array + * @param string $pattern + * @param array|string $paths */ - public function getConverters() {} + public function reConfigure(string $pattern, $paths = null) {} /** * Resets the internal route id generator @@ -173,17 +178,28 @@ public function getConverters() {} public static function reset() {} /** - * Set the routing delimiter + * Sets the route's description * - * @param string $delimiter + * @param string $description + * @return RouteInterface */ - public static function delimiter($delimiter = null) {} + public function setDescription(string $description): RouteInterface {} /** - * Get routing delimiter + * Sets the route's name * - * @return string + * ```php + * $router->add( + * "/about", + * [ + * "controller" => "about", + * ] + * )->setName("about"); + * ``` + * + * @param string $name + * @return RouteInterface */ - public static function getDelimiter() {} + public function setName(string $name): RouteInterface {} } diff --git a/src/Phalcon/cli/router/RouteInterface.php b/src/Phalcon/cli/router/RouteInterface.php index cec93a31..d5cff844 100644 --- a/src/Phalcon/cli/router/RouteInterface.php +++ b/src/Phalcon/cli/router/RouteInterface.php @@ -3,81 +3,110 @@ namespace Phalcon\Cli\Router; /** - * Phalcon\Cli\Router\RouteInterface - * * Interface for Phalcon\Cli\Router\Route */ interface RouteInterface { /** - * Replaces placeholders from pattern returning a valid PCRE regular expression + * Replaces placeholders from pattern returning a valid PCRE regular + * expression * * @param string $pattern * @return string */ - public function compilePattern($pattern); + public function compilePattern(string $pattern): string; /** - * Reconfigure the route adding a new pattern and a set of paths + * Set the routing delimiter * - * @param string $pattern - * @param mixed $paths + * @param string $delimiter */ - public function reConfigure($pattern, $paths = null); + public static function delimiter(string $delimiter = null); /** - * Returns the route's name + * Returns the route's pattern * * @return string */ - public function getName(); + public function getCompiledPattern(): string; /** - * Sets the route's name + * Get routing delimiter * - * @param string $name + * @return string */ - public function setName($name); + public static function getDelimiter(): string; /** - * Returns the route's id + * Returns the route's description * * @return string */ - public function getRouteId(); + public function getDescription(): string; /** - * Returns the route's pattern + * Returns the route's name * * @return string */ - public function getPattern(); + public function getName(): string; + + /** + * Returns the paths + * + * @return array + */ + public function getPaths(): array; /** * Returns the route's pattern * * @return string */ - public function getCompiledPattern(); + public function getPattern(): string; /** - * Returns the paths + * Returns the paths using positions as keys and names as values * * @return array */ - public function getPaths(); + public function getReversedPaths(): array; /** - * Returns the paths using positions as keys and names as values + * Returns the route's id * - * @return array + * @return string + */ + public function getRouteId(): string; + + /** + * Reconfigure the route adding a new pattern and a set of paths + * + * @param string $pattern + * @param mixed $paths */ - public function getReversedPaths(); + public function reConfigure(string $pattern, $paths = null); /** * Resets the internal route id generator */ public static function reset(); + /** + * Sets the route's description + * + * @param string $description + * @return RouteInterface + */ + public function setDescription(string $description): RouteInterface; + + /** + * Sets the route's name + * + * @param string $name + * @return RouteInterface + */ + public function setName(string $name): RouteInterface; + } diff --git a/src/Phalcon/collection/Exception.php b/src/Phalcon/collection/Exception.php new file mode 100644 index 00000000..58194464 --- /dev/null +++ b/src/Phalcon/collection/Exception.php @@ -0,0 +1,11 @@ + "path/config", + * "adapter" => "php", + * ]; + * + * $config = (new ConfigFactory())->load($options); + * ``` + */ +class ConfigFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * ConfigFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Load a config to create a new instance + * + * @param mixed $config + * @return object + */ + public function load($config) {} + + /** + * Returns a new Config instance + * + * @param string $name + * @param string $fileName + * @param mixed $params + * @return object + */ + public function newInstance(string $name, string $fileName, $params = null) {} + + /** + * Returns the adapters for the factory + * + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/config/Exception.php b/src/Phalcon/config/Exception.php index f365baad..80954ccc 100644 --- a/src/Phalcon/config/Exception.php +++ b/src/Phalcon/config/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Config; /** - * Phalcon\Config\Exception - * * Exceptions thrown in Phalcon\Config will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/config/Factory.php b/src/Phalcon/config/Factory.php deleted file mode 100644 index 1fe15287..00000000 --- a/src/Phalcon/config/Factory.php +++ /dev/null @@ -1,33 +0,0 @@ - - * use Phalcon\Config\Factory; - * - * $options = [ - * "filePath" => "path/config", - * "adapter" => "php", - * ]; - * $config = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return \Phalcon\Config - */ - public static function load($config) {} - - /** - * @param string $namespace - * @param mixed $config - */ - protected static function loadClass($namespace, $config) {} - -} diff --git a/src/Phalcon/config/adapter/Grouped.php b/src/Phalcon/config/adapter/Grouped.php index 348b9b5f..5de00ac0 100644 --- a/src/Phalcon/config/adapter/Grouped.php +++ b/src/Phalcon/config/adapter/Grouped.php @@ -3,13 +3,11 @@ namespace Phalcon\Config\Adapter; /** - * Phalcon\Config\Adapter\Grouped - * * Reads multiple files (or arrays) and merges them all together. * - * @see Phalcon\Config\Factory::load To load Config Adapter class using 'adapter' option. + * See `Phalcon\Config\Factory::load` To load Config Adapter class using 'adapter' option. * - * + * ```php * use Phalcon\Config\Adapter\Grouped; * * $config = new Grouped( @@ -18,9 +16,9 @@ * "path/to/config.dist.php", * ] * ); - * + * ``` * - * + * ```php * use Phalcon\Config\Adapter\Grouped; * * $config = new Grouped( @@ -30,9 +28,9 @@ * ], * "json" * ); - * + * ``` * - * + * ```php * use Phalcon\Config\Adapter\Grouped; * * $config = new Grouped( @@ -49,10 +47,11 @@ * "adapter" => "array", * "config" => [ * "property" => "value", + * ], * ], * ], * ); - * + * ``` */ class Grouped extends \Phalcon\Config { @@ -63,6 +62,6 @@ class Grouped extends \Phalcon\Config * @param array $arrayConfig * @param string $defaultAdapter */ - public function __construct(array $arrayConfig, $defaultAdapter = 'php') {} + public function __construct(array $arrayConfig, string $defaultAdapter = 'php') {} } diff --git a/src/Phalcon/config/adapter/Ini.php b/src/Phalcon/config/adapter/Ini.php index 63694376..d2679230 100644 --- a/src/Phalcon/config/adapter/Ini.php +++ b/src/Phalcon/config/adapter/Ini.php @@ -3,13 +3,11 @@ namespace Phalcon\Config\Adapter; /** - * Phalcon\Config\Adapter\Ini - * * Reads ini files and converts them to Phalcon\Config objects. * * Given the next configuration file: * - * + * ```ini * [database] * adapter = Mysql * host = localhost @@ -21,68 +19,58 @@ * controllersDir = "../app/controllers/" * modelsDir = "../app/models/" * viewsDir = "../app/views/" - * + * ``` * * You can read it as follows: * - * - * $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + * ```php + * use Phalcon\Config\Adapter\Ini; + * + * $config = new Ini("path/config.ini"); * * echo $config->phalcon->controllersDir; * echo $config->database->username; - * + * ``` * * PHP constants may also be parsed in the ini file, so if you define a constant * as an ini value before calling the constructor, the constant's value will be * integrated into the results. To use it this way you must specify the optional - * second parameter as INI_SCANNER_NORMAL when calling the constructor: + * second parameter as `INI_SCANNER_NORMAL` when calling the constructor: * - * + * ```php * $config = new \Phalcon\Config\Adapter\Ini( * "path/config-with-constants.ini", * INI_SCANNER_NORMAL * ); - * + * ``` */ class Ini extends \Phalcon\Config { /** - * Phalcon\Config\Adapter\Ini constructor + * Ini constructor. * * @param string $filePath * @param mixed $mode */ - public function __construct($filePath, $mode = null) {} + public function __construct(string $filePath, $mode = null) {} /** - * Build multidimensional array from string - * - * - * $this->_parseIniString("path.hello.world", "value for last key"); + * We have to cast values manually because parse_ini_file() has a poor + * implementation. * - * // result - * [ - * "path" => [ - * "hello" => [ - * "world" => "value for last key", - * ], - * ], - * ]; - * - * - * @param string $path - * @param mixed $value - * @return array + * @param mixed $ini + * @return bool|null|double|int|string */ - protected function _parseIniString($path, $value) {} + protected function cast($ini) {} /** - * We have to cast values manually because parse_ini_file() has a poor implementation. + * Build multidimensional array from string * - * @param mixed $ini The array casted by `parse_ini_file` - * @return bool|null|double|int|string + * @param string $path + * @param mixed $value + * @return array */ - protected function _cast($ini) {} + protected function parseIniString(string $path, $value): array {} } diff --git a/src/Phalcon/config/adapter/Json.php b/src/Phalcon/config/adapter/Json.php index 5c9f5761..6f20d09f 100644 --- a/src/Phalcon/config/adapter/Json.php +++ b/src/Phalcon/config/adapter/Json.php @@ -3,24 +3,24 @@ namespace Phalcon\Config\Adapter; /** - * Phalcon\Config\Adapter\Json - * * Reads JSON files and converts them to Phalcon\Config objects. * * Given the following configuration file: * - * + * ```json * {"phalcon":{"baseuri":"\/phalcon\/"},"models":{"metadata":"memory"}} - * + * ``` * * You can read it as follows: * - * - * $config = new Phalcon\Config\Adapter\Json("path/config.json"); + * ```php + * use Phalcon\Config\Adapter\Json; + * + * $config = new Json("path/config.json"); * * echo $config->phalcon->baseuri; * echo $config->models->metadata; - * + * ``` */ class Json extends \Phalcon\Config { @@ -30,6 +30,6 @@ class Json extends \Phalcon\Config * * @param string $filePath */ - public function __construct($filePath) {} + public function __construct(string $filePath) {} } diff --git a/src/Phalcon/config/adapter/Php.php b/src/Phalcon/config/adapter/Php.php index 844d44e6..cea8c07c 100644 --- a/src/Phalcon/config/adapter/Php.php +++ b/src/Phalcon/config/adapter/Php.php @@ -3,13 +3,11 @@ namespace Phalcon\Config\Adapter; /** - * Phalcon\Config\Adapter\Php - * * Reads php files and converts them to Phalcon\Config objects. * * Given the next configuration file: * - * + * ```php * "../app/views/", * ], * ]; - * + * ``` * * You can read it as follows: * - * - * $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + * ```php + * use Phalcon\Config\Adapter\Php; + * + * $config = new Php("path/config.php"); * * echo $config->phalcon->controllersDir; * echo $config->database->username; - * + * ``` */ class Php extends \Phalcon\Config { @@ -45,6 +45,6 @@ class Php extends \Phalcon\Config * * @param string $filePath */ - public function __construct($filePath) {} + public function __construct(string $filePath) {} } diff --git a/src/Phalcon/config/adapter/Yaml.php b/src/Phalcon/config/adapter/Yaml.php index a0beca14..b0d7dc11 100644 --- a/src/Phalcon/config/adapter/Yaml.php +++ b/src/Phalcon/config/adapter/Yaml.php @@ -3,29 +3,29 @@ namespace Phalcon\Config\Adapter; /** - * Phalcon\Config\Adapter\Yaml - * * Reads YAML files and converts them to Phalcon\Config objects. * * Given the following configuration file: * - * + * ```yaml * phalcon: * baseuri: /phalcon/ * controllersDir: !approot /app/controllers/ * models: * metadata: memory - * + * ``` * * You can read it as follows: * - * + * ```php * define( * "APPROOT", * dirname(__DIR__) * ); * - * $config = new \Phalcon\Config\Adapter\Yaml( + * use Phalcon\Config\Adapter\Yaml; + * + * $config = new Yaml( * "path/config.yaml", * [ * "!approot" => function($value) { @@ -37,7 +37,7 @@ * echo $config->phalcon->controllersDir; * echo $config->phalcon->baseuri; * echo $config->models->metadata; - * + * ``` */ class Yaml extends \Phalcon\Config { @@ -45,10 +45,9 @@ class Yaml extends \Phalcon\Config /** * Phalcon\Config\Adapter\Yaml constructor * - * @throws \Phalcon\Config\Exception * @param string $filePath * @param array $callbacks */ - public function __construct($filePath, array $callbacks = null) {} + public function __construct(string $filePath, array $callbacks = null) {} } diff --git a/src/Phalcon/crypt/CryptInterface.php b/src/Phalcon/crypt/CryptInterface.php new file mode 100644 index 00000000..2758e631 --- /dev/null +++ b/src/Phalcon/crypt/CryptInterface.php @@ -0,0 +1,137 @@ + "192.168.0.11", + * "username" => "sigma", + * "password" => "secret", + * "dbname" => "blog", + * "port" => "3306", + * ] + * ); + * + * $result = $connection->query( + * "SELECT FROM robots LIMIT 5" + * ); + * + * $result->setFetchMode(Enum::FETCH_NUM); + * + * while ($robot = $result->fetch()) { + * print_r($robot); + * } + * } catch (Exception $e) { + * echo $e->getMessage(), PHP_EOL; + * } + * ``` + */ +abstract class AbstractDb +{ + + /** + * Enables/disables options in the Database component + * + * @param array $options + */ + public static function setup(array $options) {} + +} diff --git a/src/Phalcon/db/Column.php b/src/Phalcon/db/Column.php index 4c08e763..30f71f34 100644 --- a/src/Phalcon/db/Column.php +++ b/src/Phalcon/db/Column.php @@ -3,11 +3,9 @@ namespace Phalcon\Db; /** - * Phalcon\Db\Column - * * Allows to define columns to be used on create or alter table operations * - * + * ```php * use Phalcon\Db\Column as Column; * * // Column definition @@ -25,188 +23,198 @@ * * // Add column to existing table * $connection->addColumn("robots", null, $column); - * + * ``` */ class Column implements \Phalcon\Db\ColumnInterface { /** - * Integer abstract type + * Bind Type Blob */ - const TYPE_INTEGER = 0; + const BIND_PARAM_BLOB = 3; /** - * Date abstract type + * Bind Type Bool */ - const TYPE_DATE = 1; + const BIND_PARAM_BOOL = 5; /** - * Varchar abstract type + * Bind Type Decimal */ - const TYPE_VARCHAR = 2; + const BIND_PARAM_DECIMAL = 32; /** - * Decimal abstract type + * Bind Type Integer */ - const TYPE_DECIMAL = 3; + const BIND_PARAM_INT = 1; /** - * Datetime abstract type + * Bind Type Null */ - const TYPE_DATETIME = 4; + const BIND_PARAM_NULL = 0; /** - * Char abstract type + * Bind Type String */ - const TYPE_CHAR = 5; + const BIND_PARAM_STR = 2; /** - * Text abstract data type + * Skip binding by type */ - const TYPE_TEXT = 6; + const BIND_SKIP = 1024; /** - * Float abstract data type + * Big integer abstract data type */ - const TYPE_FLOAT = 7; + const TYPE_BIGINTEGER = 14; /** - * Boolean abstract data type + * Bit abstract data type + */ + const TYPE_BIT = 19; + + /** + * Blob abstract data type + */ + const TYPE_BLOB = 11; + + /** + * Bool abstract data type */ const TYPE_BOOLEAN = 8; /** - * Double abstract data type + * Char abstract data type */ - const TYPE_DOUBLE = 9; + const TYPE_CHAR = 5; /** - * Tinyblob abstract data type + * Date abstract data type */ - const TYPE_TINYBLOB = 10; + const TYPE_DATE = 1; /** - * Blob abstract data type + * Datetime abstract data type */ - const TYPE_BLOB = 11; + const TYPE_DATETIME = 4; /** - * Mediumblob abstract data type + * Decimal abstract data type */ - const TYPE_MEDIUMBLOB = 12; + const TYPE_DECIMAL = 3; /** - * Longblob abstract data type + * Double abstract data type */ - const TYPE_LONGBLOB = 13; + const TYPE_DOUBLE = 9; /** - * Big integer abstract data type + * Enum abstract data type */ - const TYPE_BIGINTEGER = 14; + const TYPE_ENUM = 18; /** - * Json abstract type + * Float abstract data type + */ + const TYPE_FLOAT = 7; + + /** + * Int abstract data type + */ + const TYPE_INTEGER = 0; + + /** + * Json abstract data type */ const TYPE_JSON = 15; /** - * Jsonb abstract type + * Jsonb abstract data type */ const TYPE_JSONB = 16; /** - * Datetime abstract type + * Longblob abstract data type */ - const TYPE_TIMESTAMP = 17; + const TYPE_LONGBLOB = 13; /** - * Bind Type Null + * Longtext abstract data type */ - const BIND_PARAM_NULL = 0; + const TYPE_LONGTEXT = 24; /** - * Bind Type Integer + * Mediumblob abstract data type */ - const BIND_PARAM_INT = 1; + const TYPE_MEDIUMBLOB = 12; /** - * Bind Type String + * Mediumintegerr abstract data type */ - const BIND_PARAM_STR = 2; + const TYPE_MEDIUMINTEGER = 21; /** - * Bind Type Blob + * Mediumtext abstract data type */ - const BIND_PARAM_BLOB = 3; + const TYPE_MEDIUMTEXT = 23; /** - * Bind Type Bool + * Smallint abstract data type */ - const BIND_PARAM_BOOL = 5; + const TYPE_SMALLINTEGER = 22; /** - * Bind Type Decimal + * Text abstract data type */ - const BIND_PARAM_DECIMAL = 32; + const TYPE_TEXT = 6; /** - * Skip binding by type + * Time abstract data type */ - const BIND_SKIP = 1024; + const TYPE_TIME = 20; /** - * Column's name - * - * @var string + * Timestamp abstract data type */ - protected $_name; + const TYPE_TIMESTAMP = 17; /** - * Schema which table related is - * - * @var string + * Tinyblob abstract data type */ - protected $_schemaName; + const TYPE_TINYBLOB = 10; /** - * Column data type - * - * @var int|string + * Tinyint abstract data type */ - protected $_type; + const TYPE_TINYINTEGER = 26; /** - * Column data type reference - * - * @var int + * Tinytext abstract data type */ - protected $_typeReference = -1; + const TYPE_TINYTEXT = 25; /** - * Column data type values - * - * @var array|string + * Varchar abstract data type */ - protected $_typeValues; + const TYPE_VARCHAR = 2; /** - * The column have some numeric type? + * Column Position + * + * @var string */ - protected $_isNumeric = false; + protected $after; /** - * Integer column size + * Column is autoIncrement? * - * @var int + * @var bool */ - protected $_size = 0; + protected $autoIncrement = false; /** - * Integer column number scale - * - * @var int + * Bind Type */ - protected $_scale = 0; + protected $bindType = 2; /** * Default column value @@ -214,104 +222,125 @@ class Column implements \Phalcon\Db\ColumnInterface protected $_default = null; /** - * Integer column unsigned? + * Position is first + * + * @var bool + */ + protected $first = false; + + /** + * The column have some numeric type? + */ + protected $isNumeric = false; + + /** + * Column's name * - * @var boolean + * @var string */ - protected $_unsigned = false; + protected $name; /** * Column not nullable? * - * @var boolean + * @var bool */ - protected $_notNull = false; + protected $notNull = false; /** * Column is part of the primary key? */ - protected $_primary = false; + protected $primary = false; /** - * Column is autoIncrement? + * Integer column number scale * - * @var boolean + * @var int */ - protected $_autoIncrement = false; + protected $scale = 0; /** - * Position is first + * Integer column size * - * @var boolean + * @var int */ - protected $_first = false; + protected $size = 0; /** - * Column Position + * Column data type * - * @var string + * @var int */ - protected $_after; + protected $type; /** - * Bind Type + * Column data type reference + * + * @var int */ - protected $_bindType = 2; - + protected $typeReference = -1; /** - * Column's name + * Column data type values * - * @return string + * @var array|string */ - public function getName() {} + protected $typeValues; /** - * Schema which table related is + * Integer column unsigned? * - * @return string + * @var bool */ - public function getSchemaName() {} + protected $unsigned = false; + /** - * Column data type + * Default column value + */ + public function getDefault() {} + + /** + * Column's name * - * @return int|string + * @return string */ - public function getType() {} + public function getName(): string {} /** - * Column data type reference + * Integer column number scale * * @return int */ - public function getTypeReference() {} + public function getScale(): int {} /** - * Column data type values + * Integer column size * - * @return array|string + * @return int */ - public function getTypeValues() {} + public function getSize(): int {} /** - * Integer column size + * Column data type * * @return int */ - public function getSize() {} + public function getType(): int {} /** - * Integer column number scale + * Column data type reference * * @return int */ - public function getScale() {} + public function getTypeReference(): int {} /** - * Default column value + * Column data type values + * + * @return array|string */ - public function getDefault() {} + public function getTypeValues() {} /** * Phalcon\Db\Column constructor @@ -319,77 +348,69 @@ public function getDefault() {} * @param string $name * @param array $definition */ - public function __construct($name, array $definition) {} + public function __construct(string $name, array $definition) {} /** - * Returns true if number column is unsigned + * Check whether field absolute to position in table * - * @return bool + * @return string */ - public function isUnsigned() {} + public function getAfterPosition(): string {} /** - * Not null + * Returns the type of bind handling * - * @return bool + * @return int */ - public function isNotNull() {} + public function getBindType(): int {} /** - * Column is part of the primary key? + * Check whether column has default value * * @return bool */ - public function isPrimary() {} + public function hasDefault(): bool {} /** * Auto-Increment * * @return bool */ - public function isAutoIncrement() {} - - /** - * Check whether column have an numeric type - * - * @return bool - */ - public function isNumeric() {} + public function isAutoIncrement(): bool {} /** * Check whether column have first position in table * * @return bool */ - public function isFirst() {} + public function isFirst(): bool {} /** - * Check whether field absolute to position in table + * Not null * - * @return string + * @return bool */ - public function getAfterPosition() {} + public function isNotNull(): bool {} /** - * Returns the type of bind handling + * Check whether column have an numeric type * - * @return int + * @return bool */ - public function getBindType() {} + public function isNumeric(): bool {} /** - * Restores the internal state of a Phalcon\Db\Column object + * Column is part of the primary key? * - * @param array $data - * @return \Phalcon\Db\ColumnInterface + * @return bool */ - public static function __set_state(array $data) {} + public function isPrimary(): bool {} /** - * Check whether column has default value + * Returns true if number column is unsigned * * @return bool */ - public function hasDefault() {} + public function isUnsigned(): bool {} } diff --git a/src/Phalcon/db/ColumnInterface.php b/src/Phalcon/db/ColumnInterface.php index dcf8d0c1..2fc8226d 100644 --- a/src/Phalcon/db/ColumnInterface.php +++ b/src/Phalcon/db/ColumnInterface.php @@ -3,138 +3,121 @@ namespace Phalcon\Db; /** - * Phalcon\Db\ColumnInterface - * * Interface for Phalcon\Db\Column */ interface ColumnInterface { /** - * Returns schema's table related to column + * Check whether field absolute to position in table * * @return string */ - public function getSchemaName(); + public function getAfterPosition(): string; /** - * Returns column name + * Returns the type of bind handling * - * @return string + * @return int */ - public function getName(); + public function getBindType(): int; /** - * Returns column type + * Returns default value of column * - * @return int + * @return mixed */ - public function getType(); + public function getDefault(); /** - * Returns column type reference + * Returns column name * - * @return int + * @return string */ - public function getTypeReference(); + public function getName(): string; /** - * Returns column type values + * Returns column scale * * @return int */ - public function getTypeValues(); + public function getScale(): int; /** * Returns column size * * @return int */ - public function getSize(); + public function getSize(): int; /** - * Returns column scale + * Returns column type * * @return int */ - public function getScale(); + public function getType(): int; /** - * Returns true if number column is unsigned + * Returns column type reference * - * @return boolean + * @return int */ - public function isUnsigned(); + public function getTypeReference(): int; /** - * Not null + * Returns column type values * - * @return boolean + * @return array|string */ - public function isNotNull(); + public function getTypeValues(); /** - * Column is part of the primary key? + * Check whether column has default value * - * @return boolean + * @return bool */ - public function isPrimary(); + public function hasDefault(): bool; /** * Auto-Increment * - * @return boolean - */ - public function isAutoIncrement(); - - /** - * Check whether column have an numeric type - * - * @return boolean + * @return bool */ - public function isNumeric(); + public function isAutoIncrement(): bool; /** * Check whether column have first position in table * - * @return boolean - */ - public function isFirst(); - - /** - * Check whether field absolute to position in table - * - * @return string + * @return bool */ - public function getAfterPosition(); + public function isFirst(): bool; /** - * Returns the type of bind handling + * Not null * - * @return int + * @return bool */ - public function getBindType(); + public function isNotNull(): bool; /** - * Returns default value of column + * Check whether column have an numeric type * - * @return int + * @return bool */ - public function getDefault(); + public function isNumeric(): bool; /** - * Check whether column has default value + * Column is part of the primary key? * * @return bool */ - public function hasDefault(); + public function isPrimary(): bool; /** - * Restores the internal state of a Phalcon\Db\Column object + * Returns true if number column is unsigned * - * @param array $data - * @return ColumnInterface + * @return bool */ - public static function __set_state(array $data); + public function isUnsigned(): bool; } diff --git a/src/Phalcon/db/Dialect.php b/src/Phalcon/db/Dialect.php index d6021102..f72935c0 100644 --- a/src/Phalcon/db/Dialect.php +++ b/src/Phalcon/db/Dialect.php @@ -3,44 +3,25 @@ namespace Phalcon\Db; /** - * Phalcon\Db\Dialect - * * This is the base class to each database dialect. This implements * common methods to transform intermediate code into its RDBMS related syntax */ abstract class Dialect implements \Phalcon\Db\DialectInterface { - protected $_escapeChar; + protected $escapeChar; - protected $_customFunctions; + protected $customFunctions; /** - * Registers custom SQL functions + * Generate SQL to create a new savepoint * * @param string $name - * @param callable $customFunction - * @return Dialect - */ - public function registerCustomFunction($name, $customFunction) {} - - /** - * Returns registered functions - * - * @return array - */ - public function getCustomFunctions() {} - - /** - * Escape Schema - * - * @param string $str - * @param string $escapeChar * @return string */ - public final function escapeSchema($str, $escapeChar = null) {} + public function createSavepoint(string $name): string {} /** * Escape identifiers @@ -49,56 +30,56 @@ public final function escapeSchema($str, $escapeChar = null) {} * @param string $escapeChar * @return string */ - public final function escape($str, $escapeChar = null) {} + final public function escape(string $str, string $escapeChar = null): string {} /** - * Generates the SQL for LIMIT clause - * - * - * $sql = $dialect->limit("SELECT FROM robots", 10); - * echo $sql; // SELECT FROM robots LIMIT 10 - * - * $sql = $dialect->limit("SELECT FROM robots", [10, 50]); - * echo $sql; // SELECT FROM robots LIMIT 10 OFFSET 50 - * + * Escape Schema * - * @param string $sqlQuery - * @param mixed $number + * @param string $str + * @param string $escapeChar * @return string */ - public function limit($sqlQuery, $number) {} + final public function escapeSchema(string $str, string $escapeChar = null): string {} /** * Returns a SQL modified with a FOR UPDATE clause * - * + * ```php * $sql = $dialect->forUpdate("SELECT FROM robots"); + * * echo $sql; // SELECT FROM robots FOR UPDATE - * + * ``` * * @param string $sqlQuery * @return string */ - public function forUpdate($sqlQuery) {} + public function forUpdate(string $sqlQuery): string {} /** * Gets a list of columns with escaped identifiers * - * + * ```php * echo $dialect->getColumnList( * [ * "column1", * "column", * ] * ); - * + * ``` * * @param array $columnList * @param string $escapeChar * @param mixed $bindCounts * @return string */ - public final function getColumnList(array $columnList, $escapeChar = null, $bindCounts = null) {} + final public function getColumnList(array $columnList, string $escapeChar = null, $bindCounts = null): string {} + + /** + * Returns registered functions + * + * @return array + */ + public function getCustomFunctions(): array {} /** * Resolve Column expressions @@ -108,7 +89,7 @@ public final function getColumnList(array $columnList, $escapeChar = null, $bind * @param mixed $bindCounts * @return string */ - public final function getSqlColumn($column, $escapeChar = null, $bindCounts = null) {} + final public function getSqlColumn($column, string $escapeChar = null, $bindCounts = null): string {} /** * Transforms an intermediate representation for an expression into a database system valid expression @@ -118,16 +99,65 @@ public final function getSqlColumn($column, $escapeChar = null, $bindCounts = nu * @param mixed $bindCounts * @return string */ - public function getSqlExpression(array $expression, $escapeChar = null, $bindCounts = null) {} + public function getSqlExpression(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Transform an intermediate representation of a schema/table into a database system valid expression + * Transform an intermediate representation of a schema/table into a + * database system valid expression * * @param mixed $table * @param string $escapeChar * @return string */ - public final function getSqlTable($table, $escapeChar = null) {} + final public function getSqlTable($table, string $escapeChar = null): string {} + + /** + * Generates the SQL for LIMIT clause + * + * ```php + * // SELECT FROM robots LIMIT 10 + * echo $dialect->limit( + * "SELECT FROM robots", + * 10 + * ); + * + * // SELECT FROM robots LIMIT 10 OFFSET 50 + * echo $dialect->limit( + * "SELECT FROM robots", + * [10, 50] + * ); + * ``` + * + * @param string $sqlQuery + * @param mixed $number + * @return string + */ + public function limit(string $sqlQuery, $number): string {} + + /** + * Registers custom SQL functions + * + * @param string $name + * @param callable $customFunction + * @return Dialect + */ + public function registerCustomFunction(string $name, $customFunction): Dialect {} + + /** + * Generate SQL to release a savepoint + * + * @param string $name + * @return string + */ + public function releaseSavepoint(string $name): string {} + + /** + * Generate SQL to rollback a savepoint + * + * @param string $name + * @return string + */ + public function rollbackSavepoint(string $name): string {} /** * Builds a SELECT statement @@ -135,222 +165,230 @@ public final function getSqlTable($table, $escapeChar = null) {} * @param array $definition * @return string */ - public function select(array $definition) {} + public function select(array $definition): string {} /** * Checks whether the platform supports savepoints * * @return bool */ - public function supportsSavepoints() {} + public function supportsSavepoints(): bool {} /** * Checks whether the platform supports releasing savepoints. * * @return bool */ - public function supportsReleaseSavepoints() {} + public function supportsReleaseSavepoints(): bool {} /** - * Generate SQL to create a new savepoint + * Returns the size of the column enclosed in parentheses * - * @param string $name + * @param ColumnInterface $column * @return string */ - public function createSavepoint($name) {} + protected function getColumnSize(ColumnInterface $column): string {} /** - * Generate SQL to release a savepoint + * Returns the column size and scale enclosed in parentheses * - * @param string $name + * @param ColumnInterface $column * @return string */ - public function releaseSavepoint($name) {} + protected function getColumnSizeAndScale(ColumnInterface $column): string {} /** - * Generate SQL to rollback a savepoint + * Checks the column type and if not string it returns the type reference * - * @param string $name + * @param ColumnInterface $column * @return string */ - public function rollbackSavepoint($name) {} + protected function checkColumnType(ColumnInterface $column): string {} /** - * Resolve Column expressions + * Checks the column type and returns the updated SQL statement * - * @param array $expression - * @param string $escapeChar - * @param mixed $bindCounts + * @param ColumnInterface $column * @return string */ - protected final function getSqlExpressionScalar(array $expression, $escapeChar = null, $bindCounts = null) {} + protected function checkColumnTypeSql(ColumnInterface $column): string {} /** - * Resolve object expressions + * Resolve * * @param array $expression * @param string $escapeChar - * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionObject(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionAll(array $expression, string $escapeChar = null): string {} /** - * Resolve qualified expressions + * Resolve binary operations expressions * * @param array $expression * @param string $escapeChar + * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionQualified(array $expression, $escapeChar = null) {} + final protected function getSqlExpressionBinaryOperations(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve binary operations expressions + * Resolve CASE expressions * * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionBinaryOperations(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionCase(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve unary operations expressions + * Resolve CAST of values * * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionUnaryOperations(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionCastValue(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve function calls + * Resolve CONVERT of values encodings * * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionFunctionCall(array $expression, $escapeChar = null, $bindCounts) {} + final protected function getSqlExpressionConvertValue(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve Lists + * Resolve a FROM clause * - * @param array $expression + * @param mixed $expression * @param string $escapeChar - * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionList(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionFrom($expression, string $escapeChar = null): string {} /** - * Resolve + * Resolve function calls * * @param array $expression * @param string $escapeChar + * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionAll(array $expression, $escapeChar = null) {} + final protected function getSqlExpressionFunctionCall(array $expression, string $escapeChar = null, $bindCounts): string {} /** - * Resolve CAST of values + * Resolve a GROUP BY clause * - * @param array $expression + * @param mixed $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionCastValue(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionGroupBy($expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve CONVERT of values encodings + * Resolve a HAVING clause * * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionConvertValue(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionHaving(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve CASE expressions + * Resolve a JOINs clause * - * @param array $expression + * @param mixed $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionCase(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionJoins($expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a FROM clause + * Resolve a LIMIT clause * * @param mixed $expression * @param string $escapeChar + * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionFrom($expression, $escapeChar = null) {} + final protected function getSqlExpressionLimit($expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a JOINs clause + * Resolve Lists * - * @param mixed $expression + * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionJoins($expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionList(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a WHERE clause + * Resolve object expressions * - * @param mixed $expression + * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionWhere($expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionObject(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a GROUP BY clause + * Resolve an ORDER BY clause * * @param mixed $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionGroupBy($expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionOrderBy($expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a HAVING clause + * Resolve qualified expressions + * + * @param array $expression + * @param string $escapeChar + * @return string + */ + final protected function getSqlExpressionQualified(array $expression, string $escapeChar = null): string {} + + /** + * Resolve Column expressions * * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionHaving(array $expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionScalar(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve an ORDER BY clause + * Resolve unary operations expressions * - * @param mixed $expression + * @param array $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionOrderBy($expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionUnaryOperations(array $expression, string $escapeChar = null, $bindCounts = null): string {} /** - * Resolve a LIMIT clause + * Resolve a WHERE clause * * @param mixed $expression * @param string $escapeChar * @param mixed $bindCounts * @return string */ - protected final function getSqlExpressionLimit($expression, $escapeChar = null, $bindCounts = null) {} + final protected function getSqlExpressionWhere($expression, string $escapeChar = null, $bindCounts = null): string {} /** * Prepares column for this RDBMS @@ -360,7 +398,7 @@ protected final function getSqlExpressionLimit($expression, $escapeChar = null, * @param string $escapeChar * @return string */ - protected function prepareColumnAlias($qualified, $alias = null, $escapeChar = null) {} + protected function prepareColumnAlias(string $qualified, string $alias = null, string $escapeChar = null): string {} /** * Prepares table for this RDBMS @@ -371,7 +409,7 @@ protected function prepareColumnAlias($qualified, $alias = null, $escapeChar = n * @param string $escapeChar * @return string */ - protected function prepareTable($table, $schema = null, $alias = null, $escapeChar = null) {} + protected function prepareTable(string $table, string $schema = null, string $alias = null, string $escapeChar = null): string {} /** * Prepares qualified for this RDBMS @@ -381,6 +419,6 @@ protected function prepareTable($table, $schema = null, $alias = null, $escapeCh * @param string $escapeChar * @return string */ - protected function prepareQualified($column, $domain = null, $escapeChar = null) {} + protected function prepareQualified(string $column, string $domain = null, string $escapeChar = null): string {} } diff --git a/src/Phalcon/db/DialectInterface.php b/src/Phalcon/db/DialectInterface.php index 5345aabd..0e8e587d 100644 --- a/src/Phalcon/db/DialectInterface.php +++ b/src/Phalcon/db/DialectInterface.php @@ -3,82 +3,105 @@ namespace Phalcon\Db; /** - * Phalcon\Db\DialectInterface - * * Interface for Phalcon\Db dialects */ interface DialectInterface { /** - * Generates the SQL for LIMIT clause + * Generates SQL to add a column to a table * - * @param string $sqlQuery - * @param mixed $number + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function limit($sqlQuery, $number); + public function addColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column): string; /** - * Returns a SQL modified with a FOR UPDATE clause + * Generates SQL to add an index to a table * - * @param string $sqlQuery + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ReferenceInterface $reference * @return string */ - public function forUpdate($sqlQuery); + public function addForeignKey(string $tableName, string $schemaName, \Phalcon\Db\ReferenceInterface $reference): string; /** - * Returns a SQL modified with a LOCK IN SHARE MODE clause + * Generates SQL to add an index to a table * - * @param string $sqlQuery + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function sharedLock($sqlQuery); + public function addIndex(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string; /** - * Builds a SELECT statement + * Generates SQL to add the primary key to a table * - * @param array $definition + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function select(array $definition); + public function addPrimaryKey(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string; /** - * Gets a list of columns + * Generate SQL to create a new savepoint * - * @param array $columnList + * @param string $name * @return string */ - public function getColumnList(array $columnList); + public function createSavepoint(string $name): string; /** - * Gets the column name in RDBMS + * Generates SQL to create a table * - * @param \Phalcon\Db\ColumnInterface $column + * @param string $tableName + * @param string $schemaName + * @param array $definition * @return string */ - public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column); + public function createTable(string $tableName, string $schemaName, array $definition): string; /** - * Generates SQL to add a column to a table + * Generates SQL to create a view * - * @param string $tableName + * @param string $viewName + * @param array $definition * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function addColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column); + public function createView(string $viewName, array $definition, string $schemaName = null): string; /** - * Generates SQL to modify a column in a table + * Generates SQL to describe a table * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn + * @param string $table + * @param string $schema * @return string */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null); + public function describeColumns(string $table, string $schema = null): string; + + /** + * Generates SQL to query indexes on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeIndexes(string $table, string $schema = null): string; + + /** + * Generates SQL to query foreign keys on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeReferences(string $table, string $schema = null): string; /** * Generates SQL to delete a column from a table @@ -88,17 +111,17 @@ public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterfac * @param string $columnName * @return string */ - public function dropColumn($tableName, $schemaName, $columnName); + public function dropColumn(string $tableName, string $schemaName, string $columnName): string; /** - * Generates SQL to add an index to a table + * Generates SQL to delete a foreign key from a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\IndexInterface $index + * @param string $referenceName * @return string */ - public function addIndex($tableName, $schemaName, \Phalcon\Db\IndexInterface $index); + public function dropForeignKey(string $tableName, string $schemaName, string $referenceName): string; /** * Generates SQL to delete an index from a table @@ -108,183 +131,186 @@ public function addIndex($tableName, $schemaName, \Phalcon\Db\IndexInterface $in * @param string $indexName * @return string */ - public function dropIndex($tableName, $schemaName, $indexName); + public function dropIndex(string $tableName, string $schemaName, string $indexName): string; /** - * Generates SQL to add the primary key to a table + * Generates SQL to delete primary key from a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addPrimaryKey($tableName, $schemaName, \Phalcon\Db\IndexInterface $index); + public function dropPrimaryKey(string $tableName, string $schemaName): string; /** - * Generates SQL to delete primary key from a table + * Generates SQL to drop a table * * @param string $tableName * @param string $schemaName * @return string */ - public function dropPrimaryKey($tableName, $schemaName); + public function dropTable(string $tableName, string $schemaName): string; /** - * Generates SQL to add an index to a table + * Generates SQL to drop a view * - * @param string $tableName + * @param string $viewName * @param string $schemaName - * @param \Phalcon\Db\ReferenceInterface $reference + * @param bool $ifExists * @return string */ - public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInterface $reference); + public function dropView(string $viewName, string $schemaName = null, bool $ifExists = true): string; /** - * Generates SQL to delete a foreign key from a table + * Returns a SQL modified with a FOR UPDATE clause * - * @param string $tableName - * @param string $schemaName - * @param string $referenceName + * @param string $sqlQuery * @return string */ - public function dropForeignKey($tableName, $schemaName, $referenceName); + public function forUpdate(string $sqlQuery): string; /** - * Generates SQL to create a table + * Gets the column name in RDBMS * - * @param string $tableName - * @param string $schemaName - * @param array $definition + * @param \Phalcon\Db\ColumnInterface $column + * @return string */ - public function createTable($tableName, $schemaName, array $definition); + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string; /** - * Generates SQL to create a view + * Gets a list of columns * - * @param string $viewName - * @param array $definition - * @param string $schemaName + * @param array $columnList * @return string */ - public function createView($viewName, array $definition, $schemaName = null); + public function getColumnList(array $columnList): string; /** - * Generates SQL to drop a table + * Returns registered functions * - * @param string $tableName - * @param string $schemaName + * @return array + */ + public function getCustomFunctions(): array; + + /** + * Transforms an intermediate representation for an expression into a + * database system valid expression + * + * @param array $expression + * @param string $escapeChar + * @param mixed $bindCounts * @return string */ - public function dropTable($tableName, $schemaName); + public function getSqlExpression(array $expression, string $escapeChar = null, $bindCounts = null): string; /** - * Generates SQL to drop a view + * Generates the SQL for LIMIT clause * - * @param string $viewName - * @param string $schemaName - * @param bool $ifExists + * @param string $sqlQuery + * @param mixed $number * @return string */ - public function dropView($viewName, $schemaName = null, $ifExists = true); + public function limit(string $sqlQuery, $number): string; /** - * Generates SQL checking for the existence of a schema.table + * List all tables in database * - * @param string $tableName * @param string $schemaName * @return string */ - public function tableExists($tableName, $schemaName = null); + public function listTables(string $schemaName = null): string; /** - * Generates SQL checking for the existence of a schema.view + * Generates SQL to modify a column in a table * - * @param string $viewName + * @param string $tableName * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return string */ - public function viewExists($viewName, $schemaName = null); + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): string; /** - * Generates SQL to describe a table + * Registers custom SQL functions * - * @param string $table - * @param string $schema - * @return string + * @param string $name + * @param callable $customFunction + * @return Dialect */ - public function describeColumns($table, $schema = null); + public function registerCustomFunction(string $name, $customFunction): Dialect; /** - * List all tables in database + * Generate SQL to release a savepoint * - * @param string $schemaName + * @param string $name * @return string */ - public function listTables($schemaName = null); + public function releaseSavepoint(string $name): string; /** - * Generates SQL to query indexes on a table + * Generate SQL to rollback a savepoint * - * @param string $table - * @param string $schema + * @param string $name * @return string */ - public function describeIndexes($table, $schema = null); + public function rollbackSavepoint(string $name): string; /** - * Generates SQL to query foreign keys on a table + * Builds a SELECT statement * - * @param string $table - * @param string $schema + * @param array $definition * @return string */ - public function describeReferences($table, $schema = null); + public function select(array $definition): string; /** - * Generates the SQL to describe the table creation options + * Returns a SQL modified with a LOCK IN SHARE MODE clause * - * @param string $table - * @param string $schema + * @param string $sqlQuery * @return string */ - public function tableOptions($table, $schema = null); + public function sharedLock(string $sqlQuery): string; /** - * Checks whether the platform supports savepoints + * Checks whether the platform supports releasing savepoints. * * @return bool */ - public function supportsSavepoints(); + public function supportsReleaseSavepoints(): bool; /** - * Checks whether the platform supports releasing savepoints. + * Checks whether the platform supports savepoints * * @return bool */ - public function supportsReleaseSavepoints(); + public function supportsSavepoints(): bool; /** - * Generate SQL to create a new savepoint + * Generates SQL checking for the existence of a schema.table * - * @param string $name + * @param string $tableName + * @param string $schemaName * @return string */ - public function createSavepoint($name); + public function tableExists(string $tableName, string $schemaName = null): string; /** - * Generate SQL to release a savepoint + * Generates the SQL to describe the table creation options * - * @param string $name + * @param string $table + * @param string $schema * @return string */ - public function releaseSavepoint($name); + public function tableOptions(string $table, string $schema = null): string; /** - * Generate SQL to rollback a savepoint + * Generates SQL checking for the existence of a schema.view * - * @param string $name + * @param string $viewName + * @param string $schemaName * @return string */ - public function rollbackSavepoint($name); + public function viewExists(string $viewName, string $schemaName = null): string; } diff --git a/src/Phalcon/db/Enum.php b/src/Phalcon/db/Enum.php new file mode 100644 index 00000000..3049c8f7 --- /dev/null +++ b/src/Phalcon/db/Enum.php @@ -0,0 +1,62 @@ + + * ```php * // Define new unique index * $index_unique = new \Phalcon\Db\Index( * 'column_UNIQUE', * [ * 'column', - * 'column' + * 'column', * ], * 'UNIQUE' * ); @@ -24,75 +22,67 @@ * $index_primary = new \Phalcon\Db\Index( * 'PRIMARY', * [ - * 'column' + * 'column', * ] * ); * * // Add index to existing table * $connection->addIndex("robots", null, $index_unique); * $connection->addIndex("robots", null, $index_primary); - * + * ``` */ class Index implements \Phalcon\Db\IndexInterface { /** - * Index name + * Index columns * - * @var string + * @var array */ - protected $_name; + protected $columns; /** - * Index columns + * Index name * - * @var array + * @var string */ - protected $_columns; + protected $name; /** * Index type * * @var string */ - protected $_type; + protected $type; /** - * Index name + * Index columns * - * @return string + * @return array */ - public function getName() {} + public function getColumns(): array {} /** - * Index columns + * Index name * - * @return array + * @return string */ - public function getColumns() {} + public function getName(): string {} /** * Index type * * @return string */ - public function getType() {} + public function getType(): string {} /** * Phalcon\Db\Index constructor * * @param string $name * @param array $columns - * @param mixed $type - */ - public function __construct($name, array $columns, $type = null) {} - - /** - * Restore a Phalcon\Db\Index object from export - * - * @param array $data - * @return IndexInterface + * @param string $type */ - public static function __set_state(array $data) {} + public function __construct(string $name, array $columns, string $type = '') {} } diff --git a/src/Phalcon/db/IndexInterface.php b/src/Phalcon/db/IndexInterface.php index 46e8eea8..036ed333 100644 --- a/src/Phalcon/db/IndexInterface.php +++ b/src/Phalcon/db/IndexInterface.php @@ -3,40 +3,30 @@ namespace Phalcon\Db; /** - * Phalcon\Db\IndexInterface - * * Interface for Phalcon\Db\Index */ interface IndexInterface { - /** - * Gets the index name - * - * @return string - */ - public function getName(); - /** * Gets the columns that corresponds the index * * @return array */ - public function getColumns(); + public function getColumns(): array; /** - * Gets the index type + * Gets the index name * * @return string */ - public function getType(); + public function getName(): string; /** - * Restore a Phalcon\Db\Index object from export + * Gets the index type * - * @param array $data - * @return IndexInterface + * @return string */ - public static function __set_state(array $data); + public function getType(): string; } diff --git a/src/Phalcon/db/Profiler.php b/src/Phalcon/db/Profiler.php index 17e3ecad..c0e49136 100644 --- a/src/Phalcon/db/Profiler.php +++ b/src/Phalcon/db/Profiler.php @@ -3,14 +3,12 @@ namespace Phalcon\Db; /** - * Phalcon\Db\Profiler - * * Instances of Phalcon\Db can generate execution profiles * on SQL statements sent to the relational database. Profiled * information includes execution time in milliseconds. * This helps you to identify bottlenecks in your applications. * - * + * ```php * use Phalcon\Db\Profiler; * use Phalcon\Events\Event; * use Phalcon\Events\Manager; @@ -52,82 +50,82 @@ * echo "Start Time: ", $profile->getInitialTime(), "\n"; * echo "Final Time: ", $profile->getFinalTime(), "\n"; * echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n"; - * + * ``` */ class Profiler { /** - * All the Phalcon\Db\Profiler\Item in the active profile + * Active Phalcon\Db\Profiler\Item * - * @var \Phalcon\Db\Profiler\Item[] + * @var Phalcon\Db\Profiler\Item */ - protected $_allProfiles; + protected $activeProfile; /** - * Active Phalcon\Db\Profiler\Item + * All the Phalcon\Db\Profiler\Item in the active profile * - * @var Phalcon\Db\Profiler\Item + * @var \Phalcon\Db\Profiler\Item[] */ - protected $_activeProfile; + protected $allProfiles; /** * Total time spent by all profiles to complete * * @var float */ - protected $_totalSeconds = 0; + protected $totalSeconds = 0; /** - * Starts the profile of a SQL sentence - * - * @param string $sqlStatement - * @param mixed $sqlVariables - * @param mixed $sqlBindTypes - * @return Profiler - */ - public function startProfile($sqlStatement, $sqlVariables = null, $sqlBindTypes = null) {} - - /** - * Stops the active profile + * Returns the last profile executed in the profiler * - * @return Profiler + * @return \Phalcon\Db\Profiler\Item */ - public function stopProfile() {} + public function getLastProfile(): Item {} /** * Returns the total number of SQL statements processed * * @return int */ - public function getNumberTotalStatements() {} + public function getNumberTotalStatements(): int {} /** * Returns the total time in seconds spent by the profiles * * @return double */ - public function getTotalElapsedSeconds() {} + public function getTotalElapsedSeconds(): float {} /** * Returns all the processed profiles * - * @return \Phalcon\Db\Profiler\Item[] + * @return array|\Phalcon\Db\Profiler\Item[] */ - public function getProfiles() {} + public function getProfiles(): array {} /** * Resets the profiler, cleaning up all the profiles * * @return Profiler */ - public function reset() {} + public function reset(): Profiler {} /** - * Returns the last profile executed in the profiler + * Starts the profile of a SQL sentence * - * @return \Phalcon\Db\Profiler\Item + * @param string $sqlStatement + * @param mixed $sqlVariables + * @param mixed $sqlBindTypes + * @return Profiler + */ + public function startProfile(string $sqlStatement, $sqlVariables = null, $sqlBindTypes = null): Profiler {} + + /** + * Stops the active profile + * + * @return Profiler */ - public function getLastProfile() {} + public function stopProfile(): Profiler {} } diff --git a/src/Phalcon/db/RawValue.php b/src/Phalcon/db/RawValue.php index 84723bd0..e4f65201 100644 --- a/src/Phalcon/db/RawValue.php +++ b/src/Phalcon/db/RawValue.php @@ -3,20 +3,18 @@ namespace Phalcon\Db; /** - * Phalcon\Db\RawValue - * * This class allows to insert/update raw data without quoting or formatting. * * The next example shows how to use the MySQL now() function as a field value. * - * + * ```php * $subscriber = new Subscribers(); * * $subscriber->email = "andres@phalconphp.com"; * $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); * * $subscriber->save(); - * + * ``` */ class RawValue { @@ -25,7 +23,7 @@ class RawValue * * @var string */ - protected $_value; + protected $value; /** @@ -33,14 +31,14 @@ class RawValue * * @return string */ - public function getValue() {} + public function getValue(): string {} /** * Raw value without quoting or formatting * * @return string */ - public function __toString() {} + public function __toString(): string {} /** * Phalcon\Db\RawValue constructor diff --git a/src/Phalcon/db/Reference.php b/src/Phalcon/db/Reference.php index c9874b1a..43eb5a35 100644 --- a/src/Phalcon/db/Reference.php +++ b/src/Phalcon/db/Reference.php @@ -3,18 +3,16 @@ namespace Phalcon\Db; /** - * Phalcon\Db\Reference - * * Allows to define reference constraints on tables * - * + * ```php * $reference = new \Phalcon\Db\Reference( * "field_fk", * [ * "referencedSchema" => "invoicing", * "referencedTable" => "products", * "columns" => [ - * "product_type", + * "producttype", * "product_code", * ], * "referencedColumns" => [ @@ -23,106 +21,122 @@ * ], * ] * ); - * + * ``` */ class Reference implements \Phalcon\Db\ReferenceInterface { + /** + * Local reference columns + * + * @var array + */ + protected $columns; + /** * Constraint name * * @var string */ - protected $_name; - + protected $name; - protected $_schemaName; - - - protected $_referencedSchema; + /** + * Referenced Columns + * + * @var array + */ + protected $referencedColumns; /** - * Referenced Table + * Referenced Schema * * @var string */ - protected $_referencedTable; + protected $referencedSchema; /** - * Local reference columns + * Referenced Table * - * @var array + * @var string */ - protected $_columns; + protected $referencedTable; /** - * Referenced Columns + * Schema name * - * @var array + * @var string */ - protected $_referencedColumns; + protected $schemaName; /** * ON DELETE * - * @var array + * @var string */ - protected $_onDelete; + protected $onDelete; /** * ON UPDATE * - * @var array + * @var string */ - protected $_onUpdate; + protected $onUpdate; + /** + * Local reference columns + * + * @return array + */ + public function getColumns(): array {} + /** * Constraint name * * @return string */ - public function getName() {} - - - public function getSchemaName() {} - + public function getName(): string {} - public function getReferencedSchema() {} + /** + * Referenced Columns + * + * @return array + */ + public function getReferencedColumns(): array {} /** - * Referenced Table + * Referenced Schema * * @return string */ - public function getReferencedTable() {} + public function getReferencedSchema(): string {} /** - * Local reference columns + * Referenced Table * - * @return array + * @return string */ - public function getColumns() {} + public function getReferencedTable(): string {} /** - * Referenced Columns + * Schema name * - * @return array + * @return string */ - public function getReferencedColumns() {} + public function getSchemaName(): string {} /** * ON DELETE * - * @return array + * @return string */ - public function getOnDelete() {} + public function getOnDelete(): string {} /** * ON UPDATE * - * @return array + * @return string */ - public function getOnUpdate() {} + public function getOnUpdate(): string {} /** * Phalcon\Db\Reference constructor @@ -130,14 +144,6 @@ public function getOnUpdate() {} * @param string $name * @param array $definition */ - public function __construct($name, array $definition) {} - - /** - * Restore a Phalcon\Db\Reference object from export - * - * @param array $data - * @return ReferenceInterface - */ - public static function __set_state(array $data) {} + public function __construct(string $name, array $definition) {} } diff --git a/src/Phalcon/db/ReferenceInterface.php b/src/Phalcon/db/ReferenceInterface.php index 735af8e1..738157ac 100644 --- a/src/Phalcon/db/ReferenceInterface.php +++ b/src/Phalcon/db/ReferenceInterface.php @@ -3,75 +3,65 @@ namespace Phalcon\Db; /** - * Phalcon\Db\Reference - * * Interface for Phalcon\Db\Reference */ interface ReferenceInterface { /** - * Gets the index name + * Gets local columns which reference is based * - * @return string + * @return array */ - public function getName(); + public function getColumns(): array; /** - * Gets the schema where referenced table is + * Gets the index name * * @return string */ - public function getSchemaName(); + public function getName(): string; /** - * Gets the schema where referenced table is + * Gets the referenced on delete * * @return string */ - public function getReferencedSchema(); - - /** - * Gets local columns which reference is based - * - * @return array - */ - public function getColumns(); + public function getOnDelete(): string; /** - * Gets the referenced table + * Gets the referenced on update * * @return string */ - public function getReferencedTable(); + public function getOnUpdate(): string; /** * Gets referenced columns * * @return array */ - public function getReferencedColumns(); + public function getReferencedColumns(): array; /** - * Gets the referenced on delete + * Gets the schema where referenced table is * * @return string */ - public function getOnDelete(); + public function getReferencedSchema(): string; /** - * Gets the referenced on update + * Gets the referenced table * * @return string */ - public function getOnUpdate(); + public function getReferencedTable(): string; /** - * Restore a Phalcon\Db\Reference object from export + * Gets the schema where referenced table is * - * @param array $data - * @return ReferenceInterface + * @return string */ - public static function __set_state(array $data); + public function getSchemaName(): string; } diff --git a/src/Phalcon/db/ResultInterface.php b/src/Phalcon/db/ResultInterface.php index 368397cc..a6baa4b2 100644 --- a/src/Phalcon/db/ResultInterface.php +++ b/src/Phalcon/db/ResultInterface.php @@ -3,74 +3,75 @@ namespace Phalcon\Db; /** - * Phalcon\Db\ResultInterface - * * Interface for Phalcon\Db\Result objects */ interface ResultInterface { /** - * Allows to executes the statement again. Some database systems don't support scrollable cursors, - * So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining + * Moves internal resultset cursor to another position letting us to fetch a + * certain row * - * @return boolean + * @param long $number */ - public function execute(); + public function dataSeek(int $number); /** - * Fetches an array/object of strings that corresponds to the fetched row, or FALSE if there are no more rows. - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode + * Allows to executes the statement again. Some database systems don't + * support scrollable cursors. So, as cursors are forward only, we need to + * execute the cursor again to fetch rows from the begining * - * @return mixed + * @return bool */ - public function fetch(); + public function execute(): bool; /** - * Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode + * Fetches an array/object of strings that corresponds to the fetched row, + * or FALSE if there are no more rows. This method is affected by the active + * fetch flag set using `Phalcon\Db\Result\Pdo::setFetchMode()` * * @return mixed */ - public function fetchArray(); + public function fetch(); /** - * Returns an array of arrays containing all the records in the result - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode + * Returns an array of arrays containing all the records in the result. This + * method is affected by the active fetch flag set using + * `Phalcon\Db\Result\Pdo::setFetchMode()` * * @return array */ - public function fetchAll(); + public function fetchAll(): array; /** - * Gets number of rows returned by a resultset + * Returns an array of strings that corresponds to the fetched row, or FALSE + * if there are no more rows. This method is affected by the active fetch + * flag set using `Phalcon\Db\Result\Pdo::setFetchMode()` * - * @return int + * @return mixed */ - public function numRows(); + public function fetchArray(); /** - * Moves internal resultset cursor to another position letting us to fetch a certain row + * Gets the internal PDO result object * - * @param int $number + * @return \PDOStatement */ - public function dataSeek($number); + public function getInternalResult(): \PDOStatement; /** - * Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch() + * Gets number of rows returned by a resultset * - * @param int $fetchMode - * @param mixed $colNoOrClassNameOrObject - * @param mixed $ctorargs - * @return bool + * @return int */ - public function setFetchMode($fetchMode, $colNoOrClassNameOrObject = null, $ctorargs = null); + public function numRows(): int; /** - * Gets the internal PDO result object + * Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch() * - * @return \PDOStatement + * @param int $fetchMode + * @return bool */ - public function getInternalResult(); + public function setFetchMode(int $fetchMode): bool; } diff --git a/src/Phalcon/db/Adapter.php b/src/Phalcon/db/adapter/AbstractAdapter.php similarity index 68% rename from src/Phalcon/db/Adapter.php rename to src/Phalcon/db/adapter/AbstractAdapter.php index 2de182e2..e6cbc176 100644 --- a/src/Phalcon/db/Adapter.php +++ b/src/Phalcon/db/adapter/AbstractAdapter.php @@ -1,101 +1,107 @@ - * // Getting first robot - * $robot = $connection->fetchOne("SELECT FROM robots"); - * print_r($robot); + * @param string $name + * @return bool + */ + public function createSavepoint(string $name): bool {} + + /** + * Creates a table * - * // Getting first robot with associative indexes only - * $robot = $connection->fetchOne("SELECT FROM robots", \Phalcon\Db::FETCH_ASSOC); - * print_r($robot); - * + * @param string $tableName + * @param string $schemaName + * @param array $definition + * @return bool + */ + public function createTable(string $tableName, string $schemaName, array $definition): bool {} + + /** + * Creates a view * - * @param string $sqlQuery - * @param mixed $fetchMode - * @param mixed $bindParams - * @param mixed $bindTypes - * @return array + * @param string $viewName + * @param array $definition + * @param string $schemaName + * @return bool + */ + public function createView(string $viewName, array $definition, string $schemaName = null): bool {} + + /** + * Deletes data from a table using custom RBDM SQL syntax + * + * ```php + * // Deleting existing robot + * $success = $connection->delete( + * "robots", + * "id = 101" + * ); + * + * // Next SQL sentence is generated + * DELETE FROM `robots` WHERE `id` = 101 + * ``` + * + * @param mixed $table + * @param mixed $whereCondition + * @param mixed $placeholders + * @param mixed $dataTypes + * @return bool + */ + public function delete($table, $whereCondition = null, $placeholders = null, $dataTypes = null): bool {} + + /** + * Lists table indexes + * + * ```php + * print_r( + * $connection->describeIndexes("robots_parts") + * ); + * ``` + * + * @param string $table + * @param string $schema + * @return array|\Phalcon\Db\IndexInterface[] */ - public function fetchOne($sqlQuery, $fetchMode = Db::FETCH_ASSOC, $bindParams = null, $bindTypes = null) {} + public function describeIndexes(string $table, string $schema = null): array {} + + /** + * Lists table references + * + * ```php + * print_r( + * $connection->describeReferences("robots_parts") + * ); + * ``` + * + * @param string $table + * @param string $schema + * @return array|\Phalcon\Db\ReferenceInterface[] + */ + public function describeReferences(string $table, string $schema = null): array {} + + /** + * Drops a column from a table + * + * @param string $tableName + * @param string $schemaName + * @param string $columnName + * @return bool + */ + public function dropColumn(string $tableName, string $schemaName, string $columnName): bool {} + + /** + * Drops a foreign key from a table + * + * @param string $tableName + * @param string $schemaName + * @param string $referenceName + * @return bool + */ + public function dropForeignKey(string $tableName, string $schemaName, string $referenceName): bool {} + + /** + * Drop an index from a table + * + * @param string $tableName + * @param string $schemaName + * @param mixed $indexName + * @return bool + */ + public function dropIndex(string $tableName, string $schemaName, $indexName): bool {} + + /** + * Drops a table's primary key + * + * @param string $tableName + * @param string $schemaName + * @return bool + */ + public function dropPrimaryKey(string $tableName, string $schemaName): bool {} + + /** + * Drops a table from a schema/database + * + * @param string $tableName + * @param string $schemaName + * @param bool $ifExists + * @return bool + */ + public function dropTable(string $tableName, string $schemaName = null, bool $ifExists = true): bool {} + + /** + * Drops a view + * + * @param string $viewName + * @param string $schemaName + * @param bool $ifExists + * @return bool + */ + public function dropView(string $viewName, string $schemaName = null, bool $ifExists = true): bool {} + + /** + * Escapes a column/table/schema name + * + * ```php + * $escapedTable = $connection->escapeIdentifier( + * "robots" + * ); + * + * $escapedTable = $connection->escapeIdentifier( + * [ + * "store", + * "robots", + * ] + * ); + * ``` + * + * @param mixed $identifier + * @return string + */ + public function escapeIdentifier($identifier): string {} /** * Dumps the complete result of a query into an array * - * + * ```php * // Getting all robots with associative indexes only * $robots = $connection->fetchAll( * "SELECT FROM robots", - * \Phalcon\Db::FETCH_ASSOC + * \Phalcon\Db\Enum::FETCH_ASSOC * ); * * foreach ($robots as $robot) { @@ -170,7 +327,7 @@ public function fetchOne($sqlQuery, $fetchMode = Db::FETCH_ASSOC, $bindParams = * // Getting all robots that contains word "robot" withing the name * $robots = $connection->fetchAll( * "SELECT FROM robots WHERE name LIKE :name", - * \Phalcon\Db::FETCH_ASSOC, + * \Phalcon\Db\Enum::FETCH_ASSOC, * [ * "name" => "%robot%", * ] @@ -178,20 +335,20 @@ public function fetchOne($sqlQuery, $fetchMode = Db::FETCH_ASSOC, $bindParams = * foreach($robots as $robot) { * print_r($robot); * } - * + * ``` * * @param string $sqlQuery * @param int $fetchMode - * @param array $bindParams - * @param array $bindTypes + * @param mixed $bindParams + * @param mixed $bindTypes * @return array */ - public function fetchAll($sqlQuery, $fetchMode = Db::FETCH_ASSOC, $bindParams = null, $bindTypes = null) {} + public function fetchAll(string $sqlQuery, int $fetchMode = Enum::FETCH_ASSOC, $bindParams = null, $bindTypes = null): array {} /** * Returns the n'th field of first row in a SQL query result * - * + * ```php * // Getting count of robots * $robotsCount = $connection->fetchColumn("SELECT count() FROM robots"); * print_r($robotsCount); @@ -202,603 +359,446 @@ public function fetchAll($sqlQuery, $fetchMode = Db::FETCH_ASSOC, $bindParams = * 1 * ); * print_r($robot); - * + * ``` * * @param string $sqlQuery * @param array $placeholders - * @param int|string $column + * @param mixed $column * @return string|bool */ - public function fetchColumn($sqlQuery, $placeholders = null, $column = 0) {} + public function fetchColumn(string $sqlQuery, array $placeholders = array(), $column = 0) {} /** - * Inserts data into a table using custom RDBMS SQL syntax + * Returns the first row in a SQL query result * - * - * // Inserting a new robot - * $success = $connection->insert( - * "robots", - * ["Astro Boy", 1952], - * ["name", "year"] - * ); + * ```php + * // Getting first robot + * $robot = $connection->fetchOne("SELECT FROM robots"); + * print_r($robot); * - * // Next SQL sentence is sent to the database system - * INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); - * + * // Getting first robot with associative indexes only + * $robot = $connection->fetchOne( + * "SELECT FROM robots", + * \Phalcon\Db\Enum::FETCH_ASSOC + * ); + * print_r($robot); + * ``` * - * @param string|array $table - * @param array $values - * @param mixed $fields - * @param mixed $dataTypes - * @param $array dataTypes - * @return bool + * @param string $sqlQuery + * @param mixed $fetchMode + * @param mixed $bindParams + * @param mixed $bindTypes + * @return array */ - public function insert($table, array $values, $fields = null, $dataTypes = null) {} + public function fetchOne(string $sqlQuery, $fetchMode = Enum::FETCH_ASSOC, $bindParams = null, $bindTypes = null): array {} /** - * Inserts data into a table using custom RBDM SQL syntax - * - * - * // Inserting a new robot - * $success = $connection->insertAsDict( - * "robots", - * [ - * "name" => "Astro Boy", - * "year" => 1952, - * ] - * ); + * Returns a SQL modified with a FOR UPDATE clause * - * // Next SQL sentence is sent to the database system - * INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); - * + * @param string $sqlQuery + * @return string + */ + public function forUpdate(string $sqlQuery): string {} + + /** + * Returns the SQL column definition from a column * - * @param mixed $table - * @param mixed $data - * @param mixed $dataTypes - * @param $string table - * @param $array dataTypes - * @return bool + * @param \Phalcon\Db\ColumnInterface $column + * @return string */ - public function insertAsDict($table, $data, $dataTypes = null) {} + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string {} /** - * Updates data on a table using custom RBDM SQL syntax + * Gets a list of columns * - * - * // Updating existing robot - * $success = $connection->update( - * "robots", - * ["name"], - * ["New Astro Boy"], - * "id = 101" - * ); + * @param mixed $columnList + * @return string + */ + public function getColumnList($columnList): string {} + + /** + * Gets the active connection unique identifier * - * // Next SQL sentence is sent to the database system - * UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + * @return string + */ + public function getConnectionId(): string {} + + /** + * Returns the default identity value to be inserted in an identity column * - * // Updating existing robot with array condition and $dataTypes - * $success = $connection->update( + * ```php + * // Inserting a new robot with a valid default value for the column 'id' + * $success = $connection->insert( * "robots", - * ["name"], - * ["New Astro Boy"], * [ - * "conditions" => "id = ?", - * "bind" => [$some_unsafe_id], - * "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + * $connection->getDefaultIdValue(), + * "Astro Boy", + * 1952, * ], * [ - * PDO::PARAM_STR + * "id", + * "name", + * "year", * ] * ); + * ``` * - * - * - * Warning! If $whereCondition is string it not escaped. - * - * @param string|array $table - * @param mixed $fields - * @param mixed $values - * @param mixed $whereCondition - * @param mixed $dataTypes - * @param $array dataTypes - * @param $string|array whereCondition - * @return bool + * @return \Phalcon\Db\RawValue */ - public function update($table, $fields, $values, $whereCondition = null, $dataTypes = null) {} + public function getDefaultIdValue(): RawValue {} /** - * Updates data on a table using custom RBDM SQL syntax - * Another, more convenient syntax + * Returns the default value to make the RBDM use the default value declared + * in the table definition * - * - * // Updating existing robot - * $success = $connection->updateAsDict( + * ```php + * // Inserting a new robot with a valid default value for the column 'year' + * $success = $connection->insert( * "robots", * [ - * "name" => "New Astro Boy", + * "Astro Boy", + * $connection->getDefaultValue() * ], - * "id = 101" + * [ + * "name", + * "year", + * ] * ); + * ``` * - * // Next SQL sentence is sent to the database system - * UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 - * - * - * @param mixed $table - * @param mixed $data - * @param mixed $whereCondition - * @param mixed $dataTypes - * @param $string whereCondition - * @param $array dataTypes - * @return bool + * @return \Phalcon\Db\RawValue */ - public function updateAsDict($table, $data, $whereCondition = null, $dataTypes = null) {} + public function getDefaultValue(): RawValue {} /** - * Deletes data from a table using custom RBDM SQL syntax - * - * - * // Deleting existing robot - * $success = $connection->delete( - * "robots", - * "id = 101" - * ); - * - * // Next SQL sentence is generated - * DELETE FROM `robots` WHERE `id` = 101 - * + * Return descriptor used to connect to the active database * - * @param string|array $table - * @param string $whereCondition - * @param array $placeholders - * @param array $dataTypes - * @return bool + * @return array */ - public function delete($table, $whereCondition = null, $placeholders = null, $dataTypes = null) {} + public function getDescriptor(): array {} /** - * Escapes a column/table/schema name - * - * - * $escapedTable = $connection->escapeIdentifier( - * "robots" - * ); - * - * $escapedTable = $connection->escapeIdentifier( - * [ - * "store", - * "robots", - * ] - * ); - * + * Returns internal dialect instance * - * @param array|string $identifier - * @return string + * @return DialectInterface */ - public function escapeIdentifier($identifier) {} + public function getDialect(): DialectInterface {} /** - * Gets a list of columns + * Returns the internal event manager * - * @param array columnList - * @return string - * @param mixed $columnList - * @return string + * @return \Phalcon\Events\ManagerInterface */ - public function getColumnList($columnList) {} + public function getEventsManager(): ManagerInterface {} /** - * Appends a LIMIT clause to $sqlQuery argument - * - * - * echo $connection->limit("SELECT FROM robots", 5); - * + * Returns the savepoint name to use for nested transactions * - * @param string $sqlQuery - * @param int $number * @return string */ - public function limit($sqlQuery, $number) {} + public function getNestedTransactionSavepointName(): string {} /** - * Generates SQL checking for the existence of a schema.table - * - * - * var_dump( - * $connection->tableExists("blog", "posts") - * ); - * + * Active SQL statement in the object without replace bound parameters * - * @param string $tableName - * @param string $schemaName - * @return bool + * @return string */ - public function tableExists($tableName, $schemaName = null) {} + public function getRealSQLStatement(): string {} /** - * Generates SQL checking for the existence of a schema.view - * - * - * var_dump( - * $connection->viewExists("active_users", "posts") - * ); - * + * Active SQL statement in the object * - * @param string $viewName - * @param string $schemaName - * @return bool + * @return array */ - public function viewExists($viewName, $schemaName = null) {} + public function getSQLBindTypes(): array {} /** - * Returns a SQL modified with a FOR UPDATE clause + * Active SQL statement in the object * - * @param string $sqlQuery * @return string */ - public function forUpdate($sqlQuery) {} + public function getSQLStatement(): string {} /** - * Returns a SQL modified with a LOCK IN SHARE MODE clause + * Inserts data into a table using custom RDBMS SQL syntax * - * @param string $sqlQuery - * @return string - */ - public function sharedLock($sqlQuery) {} - - /** - * Creates a table + * ```php + * // Inserting a new robot + * $success = $connection->insert( + * "robots", + * ["Astro Boy", 1952], + * ["name", "year"] + * ); * - * @param string $tableName - * @param string $schemaName - * @param array $definition - * @return bool - */ - public function createTable($tableName, $schemaName, array $definition) {} - - /** - * Drops a table from a schema/database + * // Next SQL sentence is sent to the database system + * INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + * ``` * - * @param string $tableName - * @param string $schemaName - * @param bool $ifExists + * @param string $table + * @param array $values + * @param mixed $fields + * @param mixed $dataTypes * @return bool */ - public function dropTable($tableName, $schemaName = null, $ifExists = true) {} + public function insert(string $table, array $values, $fields = null, $dataTypes = null): bool {} /** - * Creates a view + * Inserts data into a table using custom RBDM SQL syntax * - * @param string $viewName - * @param array $definition - * @param string $schemaName - * @return bool - */ - public function createView($viewName, array $definition, $schemaName = null) {} - - /** - * Drops a view + * ```php + * // Inserting a new robot + * $success = $connection->insertAsDict( + * "robots", + * [ + * "name" => "Astro Boy", + * "year" => 1952, + * ] + * ); * - * @param string $viewName - * @param string $schemaName - * @param bool $ifExists - * @return bool - */ - public function dropView($viewName, $schemaName = null, $ifExists = true) {} - - /** - * Adds a column to a table + * // Next SQL sentence is sent to the database system + * INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + * ``` * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column + * @param string $table + * @param mixed $data + * @param mixed $dataTypes * @return bool */ - public function addColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column) {} + public function insertAsDict(string $table, $data, $dataTypes = null): bool {} /** - * Modifies a table column based on a definition + * Returns if nested transactions should use savepoints * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn * @return bool */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null) {} + public function isNestedTransactionsWithSavepoints(): bool {} /** - * Drops a column from a table + * Appends a LIMIT clause to $sqlQuery argument * - * @param string $tableName - * @param string $schemaName - * @param string $columnName - * @return bool + * ```php + * echo $connection->limit("SELECT FROM robots", 5); + * ``` + * + * @param string $sqlQuery + * @param int $number + * @return string */ - public function dropColumn($tableName, $schemaName, $columnName) {} + public function limit(string $sqlQuery, int $number): string {} /** - * Adds an index to a table + * List all tables on a database + * + * ```php + * print_r( + * $connection->listTables("blog") + * ); + * ``` * - * @param string $tableName * @param string $schemaName - * @param IndexInterface $index - * @return bool + * @return array */ - public function addIndex($tableName, $schemaName, IndexInterface $index) {} + public function listTables(string $schemaName = null): array {} /** - * Drop an index from a table + * List all views on a database + * + * ```php + * print_r( + * $connection->listViews("blog") + * ); + * ``` * - * @param string $tableName * @param string $schemaName - * @param mixed $indexName - * @return bool + * @return array */ - public function dropIndex($tableName, $schemaName, $indexName) {} + public function listViews(string $schemaName = null): array {} /** - * Adds a primary key to a table + * Modifies a table column based on a definition * * @param string $tableName * @param string $schemaName - * @param IndexInterface $index + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return bool */ - public function addPrimaryKey($tableName, $schemaName, IndexInterface $index) {} + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): bool {} /** - * Drops a table's primary key + * Releases given savepoint * - * @param string $tableName - * @param string $schemaName + * @param string $name * @return bool */ - public function dropPrimaryKey($tableName, $schemaName) {} + public function releaseSavepoint(string $name): bool {} /** - * Adds a foreign key to a table + * Rollbacks given savepoint * - * @param string $tableName - * @param string $schemaName - * @param ReferenceInterface $reference + * @param string $name * @return bool */ - public function addForeignKey($tableName, $schemaName, ReferenceInterface $reference) {} + public function rollbackSavepoint(string $name): bool {} /** - * Drops a foreign key from a table + * Sets the event manager * - * @param string $tableName - * @param string $schemaName - * @param string $referenceName - * @return bool + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function dropForeignKey($tableName, $schemaName, $referenceName) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Returns the SQL column definition from a column + * Sets the dialect used to produce the SQL * - * @param \Phalcon\Db\ColumnInterface $column - * @return string + * @param DialectInterface $dialect */ - public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} + public function setDialect(DialectInterface $dialect) {} /** - * List all tables on a database - * - * - * print_r( - * $connection->listTables("blog") - * ); - * + * Set if nested transactions should use savepoints * - * @param string $schemaName - * @return array + * @param bool $nestedTransactionsWithSavepoints + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function listTables($schemaName = null) {} + public function setNestedTransactionsWithSavepoints(bool $nestedTransactionsWithSavepoints): AdapterInterface {} /** - * List all views on a database - * - * - * print_r( - * $connection->listViews("blog") - * ); - * + * Returns a SQL modified with a LOCK IN SHARE MODE clause * - * @param string $schemaName - * @return array + * @param string $sqlQuery + * @return string */ - public function listViews($schemaName = null) {} + public function sharedLock(string $sqlQuery): string {} /** - * Lists table indexes + * Check whether the database system requires a sequence to produce + * auto-numeric values * - * - * print_r( - * $connection->describeIndexes("robots_parts") - * ); - * - * - * @param string table - * @param string schema - * @return Phalcon\Db\Index[] - * @param string $table - * @param string $schema - * @return IndexInterface[] + * @return bool */ - public function describeIndexes($table, $schema = null) {} + public function supportSequences(): bool {} /** - * Lists table references + * Generates SQL checking for the existence of a schema.table * - * - * print_r( - * $connection->describeReferences("robots_parts") + * ```php + * var_dump( + * $connection->tableExists("blog", "posts") * ); - * + * ``` * - * @param string $table - * @param string $schema - * @return ReferenceInterface[] + * @param string $tableName + * @param string $schemaName + * @return bool */ - public function describeReferences($table, $schema = null) {} + public function tableExists(string $tableName, string $schemaName = null): bool {} /** * Gets creation options from a table * - * + * ```php * print_r( * $connection->tableOptions("robots") * ); - * + * ``` * * @param string $tableName * @param string $schemaName * @return array */ - public function tableOptions($tableName, $schemaName = null) {} - - /** - * Creates a new savepoint - * - * @param string $name - * @return bool - */ - public function createSavepoint($name) {} - - /** - * Releases given savepoint - * - * @param string $name - * @return bool - */ - public function releaseSavepoint($name) {} - - /** - * Rollbacks given savepoint - * - * @param string $name - * @return bool - */ - public function rollbackSavepoint($name) {} - - /** - * Set if nested transactions should use savepoints - * - * @param bool $nestedTransactionsWithSavepoints - * @return AdapterInterface - */ - public function setNestedTransactionsWithSavepoints($nestedTransactionsWithSavepoints) {} + public function tableOptions(string $tableName, string $schemaName = null): array {} /** - * Returns if nested transactions should use savepoints + * Updates data on a table using custom RBDM SQL syntax * - * @return bool - */ - public function isNestedTransactionsWithSavepoints() {} - - /** - * Returns the savepoint name to use for nested transactions + * ```php + * // Updating existing robot + * $success = $connection->update( + * "robots", + * ["name"], + * ["New Astro Boy"], + * "id = 101" + * ); * - * @return string - */ - public function getNestedTransactionSavepointName() {} - - /** - * Returns the default identity value to be inserted in an identity column + * // Next SQL sentence is sent to the database system + * UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 * - * - * // Inserting a new robot with a valid default value for the column 'id' - * $success = $connection->insert( + * // Updating existing robot with array condition and $dataTypes + * $success = $connection->update( * "robots", + * ["name"], + * ["New Astro Boy"], * [ - * $connection->getDefaultIdValue(), - * "Astro Boy", - * 1952, + * "conditions" => "id = ?", + * "bind" => [$some_unsafe_id], + * "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param * ], * [ - * "id", - * "name", - * "year", + * PDO::PARAM_STR * ] * ); - * * - * @return RawValue + * ``` + * + * Warning! If $whereCondition is string it not escaped. + * + * @param string $table + * @param mixed $fields + * @param mixed $values + * @param mixed $whereCondition + * @param mixed $dataTypes + * @return bool */ - public function getDefaultIdValue() {} + public function update(string $table, $fields, $values, $whereCondition = null, $dataTypes = null): bool {} /** - * Returns the default value to make the RBDM use the default value declared in the table definition + * Updates data on a table using custom RBDM SQL syntax + * Another, more convenient syntax * - * - * // Inserting a new robot with a valid default value for the column 'year' - * $success = $connection->insert( + * ```php + * // Updating existing robot + * $success = $connection->updateAsDict( * "robots", * [ - * "Astro Boy", - * $connection->getDefaultValue() + * "name" => "New Astro Boy", * ], - * [ - * "name", - * "year", - * ] + * "id = 101" * ); - * * - * @return RawValue - */ - public function getDefaultValue() {} - - /** - * Check whether the database system requires a sequence to produce auto-numeric values + * // Next SQL sentence is sent to the database system + * UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + * ``` * + * @param string $table + * @param mixed $data + * @param mixed $whereCondition + * @param mixed $dataTypes * @return bool */ - public function supportSequences() {} + public function updateAsDict(string $table, $data, $whereCondition = null, $dataTypes = null): bool {} /** - * Check whether the database system requires an explicit value for identity columns + * Check whether the database system requires an explicit value for identity + * columns * * @return bool */ - public function useExplicitIdValue() {} - - /** - * Return descriptor used to connect to the active database - * - * @return array - */ - public function getDescriptor() {} - - /** - * Gets the active connection unique identifier - * - * @return string - */ - public function getConnectionId() {} + public function useExplicitIdValue(): bool {} /** - * Active SQL statement in the object - * - * @return string - */ - public function getSQLStatement() {} - - /** - * Active SQL statement in the object without replace bound parameters + * Generates SQL checking for the existence of a schema.view * - * @return string - */ - public function getRealSQLStatement() {} - - /** - * Active SQL statement in the object + * ```php + * var_dump( + * $connection->viewExists("active_users", "posts") + * ); + * ``` * - * @return array + * @param string $viewName + * @param string $schemaName + * @return bool */ - public function getSQLBindTypes() {} + public function viewExists(string $viewName, string $schemaName = null): bool {} } diff --git a/src/Phalcon/db/AdapterInterface.php b/src/Phalcon/db/adapter/AdapterInterface.php similarity index 52% rename from src/Phalcon/db/AdapterInterface.php rename to src/Phalcon/db/adapter/AdapterInterface.php index d207a62d..e136e02f 100644 --- a/src/Phalcon/db/AdapterInterface.php +++ b/src/Phalcon/db/adapter/AdapterInterface.php @@ -1,126 +1,101 @@ fetchColumn("SELECT count() FROM robots"); + * print_r($robotsCount); + * + * // Getting name of last edited robot + * $robot = $connection->fetchColumn( + * "SELECT id, name FROM robots order by modified desc", + * 1 + * ); + * print_r($robot); + * ``` + * + * @param string $sqlQuery + * @param array $placeholders + * @param mixed $column + * @return string|bool + */ + public function fetchColumn(string $sqlQuery, array $placeholders = array(), $column = 0); + + /** + * Returns the first row in a SQL query result * + * @param string $sqlQuery + * @param int $fetchMode + * @param mixed $placeholders * @return array */ - public function getDescriptor(); + public function fetchOne(string $sqlQuery, int $fetchMode = 2, $placeholders = null): array; /** - * Gets the active connection unique identifier + * Returns a SQL modified with a FOR UPDATE clause * + * @param string $sqlQuery * @return string */ - public function getConnectionId(); + public function forUpdate(string $sqlQuery): string; /** - * Active SQL statement in the object + * Returns the SQL column definition from a column * + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function getSQLStatement(); + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string; /** - * Active SQL statement in the object without replace bound parameters + * Gets a list of columns * + * @param mixed $columnList * @return string */ - public function getRealSQLStatement(); + public function getColumnList($columnList): string; /** - * Active SQL statement in the object + * Gets the active connection unique identifier * - * @return array + * @return string */ - public function getSQLVariables(); + public function getConnectionId(): string; /** - * Active SQL statement in the object + * Return descriptor used to connect to the active database * * @return array */ - public function getSQLBindTypes(); + public function getDescriptor(): array; /** - * Returns type of database system the adapter is used for + * Returns internal dialect instance * - * @return string + * @return DialectInterface */ - public function getType(); + public function getDialect(): DialectInterface; /** * Returns the name of the dialect used * * @return string */ - public function getDialectType(); + public function getDialectType(): string; /** - * Returns internal dialect instance + * Return the default identity value to insert in an identity column * - * @return DialectInterface + * @return \Phalcon\Db\RawValue */ - public function getDialect(); + public function getDefaultIdValue(): RawValue; /** - * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor. - * Call it when you need to restore a database connection + * Return internal PDO handler * - * @param array $descriptor - * @return bool + * @return \Pdo */ - public function connect(array $descriptor = null); + public function getInternalHandler(): \Pdo; /** - * Sends SQL statements to the database server returning the success state. - * Use this method only when the SQL statement sent to the server return rows + * Returns the savepoint name to use for nested transactions * - * @param string $sqlStatement - * @param mixed $placeholders - * @param mixed $dataTypes - * @return bool|ResultInterface + * @return string */ - public function query($sqlStatement, $placeholders = null, $dataTypes = null); + public function getNestedTransactionSavepointName(): string; /** - * Sends SQL statements to the database server returning the success state. - * Use this method only when the SQL statement sent to the server doesn't return any rows + * Active SQL statement in the object without replace bound parameters * - * @param string $sqlStatement - * @param mixed $placeholders - * @param mixed $dataTypes - * @return bool + * @return string */ - public function execute($sqlStatement, $placeholders = null, $dataTypes = null); + public function getRealSQLStatement(): string; /** - * Returns the number of affected rows by the last INSERT/UPDATE/DELETE reported by the database system + * Active SQL statement in the object * - * @return int + * @return string */ - public function affectedRows(); + public function getSQLStatement(): string; /** - * Closes active connection returning success. Phalcon automatically closes - * and destroys active connections within Phalcon\Db\Pool + * Active SQL statement in the object * - * @return bool + * @return array */ - public function close(); + public function getSQLBindTypes(): array; /** - * Escapes a column/table/schema name + * Active SQL statement in the object * - * @param string $identifier - * @return string + * @return array */ - public function escapeIdentifier($identifier); + public function getSQLVariables(): array; /** - * Escapes a value to avoid SQL injections + * Returns type of database system the adapter is used for * - * @param string $str * @return string */ - public function escapeString($str); + public function getType(): string; /** - * Returns insert id for the auto_increment column inserted in the last SQL statement - * - * @param string $sequenceName - * @return int - */ - public function lastInsertId($sequenceName = null); - - /** - * Starts a transaction in the connection + * Inserts data into a table using custom RDBMS SQL syntax * - * @param bool $nesting + * @param string $table + * @param array $values + * @param mixed $fields + * @param mixed $dataTypes * @return bool */ - public function begin($nesting = true); + public function insert(string $table, array $values, $fields = null, $dataTypes = null): bool; /** - * Rollbacks the active transaction in the connection + * Inserts data into a table using custom RBDM SQL syntax * - * @param bool $nesting + * ```php + * // Inserting a new robot + * $success = $connection->insertAsDict( + * "robots", + * [ + * "name" => "Astro Boy", + * "year" => 1952, + * ] + * ); + * + * // Next SQL sentence is sent to the database system + * INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + * ``` + * + * @param string $table + * @param mixed $data + * @param mixed $dataTypes * @return bool */ - public function rollback($nesting = true); + public function insertAsDict(string $table, $data, $dataTypes = null): bool; /** - * Commits the active transaction in the connection + * Returns if nested transactions should use savepoints * - * @param bool $nesting * @return bool */ - public function commit($nesting = true); + public function isNestedTransactionsWithSavepoints(): bool; /** * Checks whether connection is under database transaction * * @return bool */ - public function isUnderTransaction(); + public function isUnderTransaction(): bool; /** - * Return internal PDO handler + * Returns insert id for the auto_increment column inserted in the last SQL + * statement * - * @return \Pdo + * @param mixed $sequenceName */ - public function getInternalHandler(); + public function lastInsertId($sequenceName = null); /** - * Lists table indexes + * Appends a LIMIT clause to sqlQuery argument * - * @param string $table - * @param string $schema - * @return IndexInterface[] + * @param string $sqlQuery + * @param int $number + * @return string */ - public function describeIndexes($table, $schema = null); + public function limit(string $sqlQuery, int $number): string; /** - * Lists table references + * List all tables on a database * - * @param string $table - * @param string $schema - * @return ReferenceInterface[] + * @param string $schemaName + * @return array */ - public function describeReferences($table, $schema = null); + public function listTables(string $schemaName = null): array; /** - * Gets creation options from a table + * List all views on a database * - * @param string $tableName * @param string $schemaName * @return array */ - public function tableOptions($tableName, $schemaName = null); + public function listViews(string $schemaName = null): array; /** - * Check whether the database system requires an explicit value for identity columns + * Modifies a table column based on a definition * + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return bool */ - public function useExplicitIdValue(); + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): bool; /** - * Return the default identity value to insert in an identity column + * Sends SQL statements to the database server returning the success state. + * Use this method only when the SQL statement sent to the server returns + * rows * - * @return RawValue + * @param string $sqlStatement + * @param mixed $placeholders + * @param mixed $dataTypes + * @return bool|ResultInterface */ - public function getDefaultIdValue(); + public function query(string $sqlStatement, $placeholders = null, $dataTypes = null); /** - * Check whether the database system requires a sequence to produce auto-numeric values + * Releases given savepoint * + * @param string $name * @return bool */ - public function supportSequences(); + public function releaseSavepoint(string $name): bool; /** - * Creates a new savepoint + * Rollbacks the active transaction in the connection * - * @param string $name + * @param bool $nesting * @return bool */ - public function createSavepoint($name); + public function rollback(bool $nesting = true): bool; /** - * Releases given savepoint + * Rollbacks given savepoint * * @param string $name * @return bool */ - public function releaseSavepoint($name); + public function rollbackSavepoint(string $name): bool; /** - * Rollbacks given savepoint + * Returns a SQL modified with a LOCK IN SHARE MODE clause * - * @param string $name - * @return bool + * @param string $sqlQuery + * @return string */ - public function rollbackSavepoint($name); + public function sharedLock(string $sqlQuery): string; /** * Set if nested transactions should use savepoints @@ -525,29 +536,87 @@ public function rollbackSavepoint($name); * @param bool $nestedTransactionsWithSavepoints * @return AdapterInterface */ - public function setNestedTransactionsWithSavepoints($nestedTransactionsWithSavepoints); + public function setNestedTransactionsWithSavepoints(bool $nestedTransactionsWithSavepoints): AdapterInterface; /** - * Returns if nested transactions should use savepoints + * Check whether the database system requires a sequence to produce + * auto-numeric values * * @return bool */ - public function isNestedTransactionsWithSavepoints(); + public function supportSequences(): bool; /** - * Returns the savepoint name to use for nested transactions + * Generates SQL checking for the existence of a schema.table * - * @return string + * @param string $tableName + * @param string $schemaName + * @return bool */ - public function getNestedTransactionSavepointName(); + public function tableExists(string $tableName, string $schemaName = null): bool; /** - * Returns an array of Phalcon\Db\Column objects describing a table + * Gets creation options from a table + * + * @param string $tableName + * @param string $schemaName + * @return array + */ + public function tableOptions(string $tableName, string $schemaName = null): array; + + /** + * Updates data on a table using custom RDBMS SQL syntax * * @param string $table - * @param string $schema - * @return ColumnInterface[] + * @param mixed $fields + * @param mixed $values + * @param mixed $whereCondition + * @param mixed $dataTypes + * @return bool + */ + public function update(string $table, $fields, $values, $whereCondition = null, $dataTypes = null): bool; + + /** + * Updates data on a table using custom RBDM SQL syntax + * Another, more convenient syntax + * + * ```php + * // Updating existing robot + * $success = $connection->updateAsDict( + * "robots", + * [ + * "name" => "New Astro Boy", + * ], + * "id = 101" + * ); + * + * // Next SQL sentence is sent to the database system + * UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + * ``` + * + * @param string $table + * @param mixed $data + * @param mixed $whereCondition + * @param mixed $dataTypes + * @return bool + */ + public function updateAsDict(string $table, $data, $whereCondition = null, $dataTypes = null): bool; + + /** + * Check whether the database system requires an explicit value for identity + * columns + * + * @return bool + */ + public function useExplicitIdValue(): bool; + + /** + * Generates SQL checking for the existence of a schema.view + * + * @param string $viewName + * @param string $schemaName + * @return bool */ - public function describeColumns($table, $schema = null); + public function viewExists(string $viewName, string $schemaName = null): bool; } diff --git a/src/Phalcon/db/adapter/PdoFactory.php b/src/Phalcon/db/adapter/PdoFactory.php new file mode 100644 index 00000000..1d71f837 --- /dev/null +++ b/src/Phalcon/db/adapter/PdoFactory.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class PdoFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * Constructor + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Factory to create an instace from a Config object + * + * @param mixed $config + * @return mixed + */ + public function load($config) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @param array $options + * @return \Phalcon\Annotations\Adapter\AbstractAdapter + */ + public function newInstance(string $name, array $options = array()): AbstractAdapter {} + + /** + * Returns the available adapters + * + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/db/adapter/Pdo.php b/src/Phalcon/db/adapter/pdo/AbstractPdo.php similarity index 75% rename from src/Phalcon/db/adapter/Pdo.php rename to src/Phalcon/db/adapter/pdo/AbstractPdo.php index 81eb783d..80be64a0 100644 --- a/src/Phalcon/db/adapter/Pdo.php +++ b/src/Phalcon/db/adapter/pdo/AbstractPdo.php @@ -1,13 +1,12 @@ + * ```php * use Phalcon\Db\Adapter\Pdo\Mysql; * * $config = [ @@ -19,21 +18,21 @@ * ]; * * $connection = new Mysql($config); - * + * ``` */ -abstract class Pdo extends \Phalcon\Db\Adapter +abstract class AbstractPdo extends \Phalcon\Db\Adapter\AbstractAdapter { /** - * PDO Handler - * - * @var \Pdo + * Last affected rows */ - protected $_pdo; + protected $affectedRows; /** - * Last affected rows + * PDO Handler + * + * @var \Pdo */ - protected $_affectedRows; + protected $pdo; /** @@ -44,11 +43,52 @@ abstract class Pdo extends \Phalcon\Db\Adapter public function __construct(array $descriptor) {} /** - * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor. + * Returns the number of affected rows by the latest INSERT/UPDATE/DELETE + * executed in the database system + * + * ```php + * $connection->execute( + * "DELETE FROM robots" + * ); + * + * echo $connection->affectedRows(), " were deleted"; + * ``` + * + * @return int + */ + public function affectedRows(): int {} + + /** + * Starts a transaction in the connection + * + * @param bool $nesting + * @return bool + */ + public function begin(bool $nesting = true): bool {} + + /** + * Commits the active transaction in the connection + * + * @param bool $nesting + * @return bool + */ + public function commit(bool $nesting = true): bool {} + + /** + * Closes the active connection returning success. Phalcon automatically + * closes and destroys active connections when the request ends + * + * @return bool + */ + public function close(): bool {} + + /** + * This method is automatically called in \Phalcon\Db\Adapter\Pdo + * constructor. * * Call it when you need to restore a database connection. * - * + * ```php * use Phalcon\Db\Adapter\Pdo\Mysql; * * // Make a connection @@ -64,97 +104,52 @@ public function __construct(array $descriptor) {} * * // Reconnect * $connection->connect(); - * + * ``` * * @param array $descriptor * @return bool */ - public function connect(array $descriptor = null) {} - - /** - * Returns a PDO prepared statement to be executed with 'executePrepared' - * - * - * use Phalcon\Db\Column; - * - * $statement = $db->prepare( - * "SELECT FROM robots WHERE name = :name" - * ); - * - * $result = $connection->executePrepared( - * $statement, - * [ - * "name" => "Voltron", - * ], - * [ - * "name" => Column::BIND_PARAM_INT, - * ] - * ); - * - * - * @param string $sqlStatement - * @return \PDOStatement - */ - public function prepare($sqlStatement) {} + public function connect(array $descriptor = null): bool {} /** - * Executes a prepared statement binding. This function uses integer indexes starting from zero - * - * - * use Phalcon\Db\Column; - * - * $statement = $db->prepare( - * "SELECT FROM robots WHERE name = :name" - * ); + * Converts bound parameters such as :name: or ?1 into PDO bind params ? * - * $result = $connection->executePrepared( - * $statement, - * [ - * "name" => "Voltron", - * ], - * [ - * "name" => Column::BIND_PARAM_INT, - * ] + * ```php + * print_r( + * $connection->convertBoundParams( + * "SELECT FROM robots WHERE name = :name:", + * [ + * "Bender", + * ] + * ) * ); - * + * ``` * - * @param \PDOStatement $statement - * @param array $placeholders - * @param array $dataTypes - * @return \PDOStatement + * @param string $sql + * @param array $params + * @return array */ - public function executePrepared(\PDOStatement $statement, array $placeholders, $dataTypes) {} + public function convertBoundParams(string $sql, array $params = array()): array {} /** - * Sends SQL statements to the database server returning the success state. - * Use this method only when the SQL statement sent to the server is returning rows + * Escapes a value to avoid SQL injections according to the active charset + * in the connection * - * - * // Querying data - * $resultset = $connection->query( - * "SELECT FROM robots WHERE type = 'mechanical'" - * ); - * - * $resultset = $connection->query( - * "SELECT FROM robots WHERE type = ?", - * [ - * "mechanical", - * ] - * ); - * + * ```php + * $escapedStr = $connection->escapeString("some dangerous value"); + * ``` * - * @param string $sqlStatement - * @param mixed $bindParams - * @param mixed $bindTypes - * @return bool|\Phalcon\Db\ResultInterface + * @param string $str + * @return string */ - public function query($sqlStatement, $bindParams = null, $bindTypes = null) {} + public function escapeString(string $str): string {} /** * Sends SQL statements to the database server returning the success state. - * Use this method only when the SQL statement sent to the server doesn't return any rows + * Use this method only when the SQL statement sent to the server doesn't + * return any rows * - * + * ```php * // Inserting data * $success = $connection->execute( * "INSERT INTO robots VALUES (1, 'Astro Boy')" @@ -167,74 +162,84 @@ public function query($sqlStatement, $bindParams = null, $bindTypes = null) {} * "Astro Boy", * ] * ); - * + * ``` * * @param string $sqlStatement * @param mixed $bindParams * @param mixed $bindTypes * @return bool */ - public function execute($sqlStatement, $bindParams = null, $bindTypes = null) {} + public function execute(string $sqlStatement, $bindParams = null, $bindTypes = null): bool {} /** - * Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system + * Executes a prepared statement binding. This function uses integer indexes + * starting from zero * - * - * $connection->execute( - * "DELETE FROM robots" + * ```php + * use Phalcon\Db\Column; + * + * $statement = $db->prepare( + * "SELECT FROM robots WHERE name = :name" * ); * - * echo $connection->affectedRows(), " were deleted"; - * + * $result = $connection->executePrepared( + * $statement, + * [ + * "name" => "Voltron", + * ], + * [ + * "name" => Column::BIND_PARAM_INT, + * ] + * ); + * ``` * - * @return int + * @param \PDOStatement $statement + * @param array $placeholders + * @param mixed $dataTypes + * @return \PDOStatement */ - public function affectedRows() {} + public function executePrepared(\PDOStatement $statement, array $placeholders, $dataTypes): \PDOStatement {} /** - * Closes the active connection returning success. Phalcon automatically closes and destroys - * active connections when the request ends - * - * @return bool + * Return the error info, if any */ - public function close() {} + public function getErrorInfo() {} /** - * Escapes a value to avoid SQL injections according to the active charset in the connection + * Return internal PDO handler * - * - * $escapedStr = $connection->escapeString("some dangerous value"); - * + * @return \Pdo + */ + public function getInternalHandler(): \Pdo {} + + /** + * Returns the current transaction nesting level * - * @param string $str - * @return string + * @return int */ - public function escapeString($str) {} + public function getTransactionLevel(): int {} /** - * Converts bound parameters such as :name: or ?1 into PDO bind params ? + * Checks whether the connection is under a transaction * - * - * print_r( - * $connection->convertBoundParams( - * "SELECT FROM robots WHERE name = :name:", - * [ - * "Bender", - * ] - * ) + * ```php + * $connection->begin(); + * + * // true + * var_dump( + * $connection->isUnderTransaction() * ); - * + * ``` * - * @param string $sql - * @param array $params - * @return array + * @return bool */ - public function convertBoundParams($sql, array $params = array()) {} + public function isUnderTransaction(): bool {} /** - * Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement + * Returns the insert id for the auto_increment/serial column inserted in + * the latest executed SQL statement * - * + * ```php * // Inserting a new robot * $success = $connection->insert( * "robots", @@ -250,72 +255,78 @@ public function convertBoundParams($sql, array $params = array()) {} * * // Getting the generated id * $id = $connection->lastInsertId(); - * + * ``` * - * @param string $sequenceName + * @param mixed $sequenceName * @return int|bool */ public function lastInsertId($sequenceName = null) {} /** - * Starts a transaction in the connection + * Returns a PDO prepared statement to be executed with 'executePrepared' * - * @param bool $nesting - * @return bool - */ - public function begin($nesting = true) {} - - /** - * Rollbacks the active transaction in the connection + * ```php + * use Phalcon\Db\Column; * - * @param bool $nesting - * @return bool - */ - public function rollback($nesting = true) {} - - /** - * Commits the active transaction in the connection + * $statement = $db->prepare( + * "SELECT FROM robots WHERE name = :name" + * ); * - * @param bool $nesting - * @return bool - */ - public function commit($nesting = true) {} - - /** - * Returns the current transaction nesting level + * $result = $connection->executePrepared( + * $statement, + * [ + * "name" => "Voltron", + * ], + * [ + * "name" => Column::BIND_PARAM_INT, + * ] + * ); + * ``` * - * @return int + * @param string $sqlStatement + * @return \PDOStatement */ - public function getTransactionLevel() {} + public function prepare(string $sqlStatement): \PDOStatement {} /** - * Checks whether the connection is under a transaction + * Sends SQL statements to the database server returning the success state. + * Use this method only when the SQL statement sent to the server is + * returning rows * - * - * $connection->begin(); + * ```php + * // Querying data + * $resultset = $connection->query( + * "SELECT FROM robots WHERE type = 'mechanical'" + * ); * - * // true - * var_dump( - * $connection->isUnderTransaction() + * $resultset = $connection->query( + * "SELECT FROM robots WHERE type = ?", + * [ + * "mechanical", + * ] * ); - * + * ``` * - * @return bool + * @param string $sqlStatement + * @param mixed $bindParams + * @param mixed $bindTypes + * @return bool|\Phalcon\Db\ResultInterface */ - public function isUnderTransaction() {} + public function query(string $sqlStatement, $bindParams = null, $bindTypes = null) {} /** - * Return internal PDO handler + * Rollbacks the active transaction in the connection * - * @return \Pdo + * @param bool $nesting + * @return bool */ - public function getInternalHandler() {} + public function rollback(bool $nesting = true): bool {} /** - * Return the error info, if any + * Returns PDO adapter DSN defaults as a key-value map. * * @return array */ - public function getErrorInfo() {} + abstract protected function getDsnDefaults(): array; } diff --git a/src/Phalcon/db/adapter/pdo/Factory.php b/src/Phalcon/db/adapter/pdo/Factory.php deleted file mode 100644 index 1a089408..00000000 --- a/src/Phalcon/db/adapter/pdo/Factory.php +++ /dev/null @@ -1,31 +0,0 @@ - - * use Phalcon\Db\Adapter\Pdo\Factory; - * - * $options = [ - * "host" => "localhost", - * "dbname" => "blog", - * "port" => 3306, - * "username" => "sigma", - * "password" => "secret", - * "adapter" => "mysql", - * ]; - * $db = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return \Phalcon\Db\AdapterInterface - */ - public static function load($config) {} - -} diff --git a/src/Phalcon/db/adapter/pdo/Mysql.php b/src/Phalcon/db/adapter/pdo/Mysql.php index 9f505dd2..7e03f623 100644 --- a/src/Phalcon/db/adapter/pdo/Mysql.php +++ b/src/Phalcon/db/adapter/pdo/Mysql.php @@ -3,11 +3,9 @@ namespace Phalcon\Db\Adapter\Pdo; /** - * Phalcon\Db\Adapter\Pdo\Mysql - * * Specific functions for the Mysql database system * - * + * ```php * use Phalcon\Db\Adapter\Pdo\Mysql; * * $config = [ @@ -19,70 +17,81 @@ * ]; * * $connection = new Mysql($config); - * + * ``` */ -class Mysql extends \Phalcon\Db\Adapter\Pdo +class Mysql extends \Phalcon\Db\Adapter\Pdo\AbstractPdo { + /** + * @var string + */ + protected $dialectType = 'mysql'; - protected $_type = 'mysql'; - + /** + * @var string + */ + protected $type = 'mysql'; - protected $_dialectType = 'mysql'; + /** + * Adds a foreign key to a table + * + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ReferenceInterface $reference + * @return bool + */ + public function addForeignKey(string $tableName, string $schemaName, \Phalcon\Db\ReferenceInterface $reference): bool {} /** * Returns an array of Phalcon\Db\Column objects describing a table * - * + * ```php * print_r( * $connection->describeColumns("posts") * ); - * + * ``` * * @param string $table * @param string $schema - * @return \Phalcon\Db\ColumnInterface[] + * @return array|\Phalcon\Db\ColumnInterface[] */ - public function describeColumns($table, $schema = null) {} + public function describeColumns(string $table, string $schema = null): array {} /** * Lists table indexes * - * + * ```php * print_r( * $connection->describeIndexes("robots_parts") * ); - * + * ``` * * @param string $table * @param string $schema - * @return \Phalcon\Db\IndexInterface[] + * @return array|\Phalcon\Db\IndexInterface[] */ - public function describeIndexes($table, $schema = null) {} + public function describeIndexes(string $table, string $schema = null): array {} /** * Lists table references * - * + * ```php * print_r( * $connection->describeReferences("robots_parts") * ); - * + * ``` * * @param string $table * @param string $schema - * @return \Phalcon\Db\ReferenceInterface[] + * @return array|\Phalcon\Db\ReferenceInterface[] */ - public function describeReferences($table, $schema = null) {} + public function describeReferences(string $table, string $schema = null): array {} /** - * Adds a foreign key to a table + * Returns PDO adapter DSN defaults as a key-value map. * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ReferenceInterface $reference - * @return bool + * @return array */ - public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInterface $reference) {} + protected function getDsnDefaults(): array {} } diff --git a/src/Phalcon/db/adapter/pdo/Postgresql.php b/src/Phalcon/db/adapter/pdo/Postgresql.php index 25eacf0b..16662427 100644 --- a/src/Phalcon/db/adapter/pdo/Postgresql.php +++ b/src/Phalcon/db/adapter/pdo/Postgresql.php @@ -3,11 +3,9 @@ namespace Phalcon\Db\Adapter\Pdo; /** - * Phalcon\Db\Adapter\Pdo\Postgresql - * * Specific functions for the Postgresql database system * - * + * ```php * use Phalcon\Db\Adapter\Pdo\Postgresql; * * $config = [ @@ -19,40 +17,36 @@ * ]; * * $connection = new Postgresql($config); - * + * ``` */ -class Postgresql extends \Phalcon\Db\Adapter\Pdo +class Postgresql extends \Phalcon\Db\Adapter\Pdo\AbstractPdo { + /** + * @var string + */ + protected $dialectType = 'postgresql'; - protected $_type = 'pgsql'; - - - protected $_dialectType = 'postgresql'; + /** + * @var string + */ + protected $type = 'pgsql'; /** - * This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. - * Call it when you need to restore a database connection. + * Constructor for Phalcon\Db\Adapter\Pdo\Postgresql * * @param array $descriptor - * @return bool */ - public function connect(array $descriptor = null) {} + public function __construct(array $descriptor) {} /** - * Returns an array of Phalcon\Db\Column objects describing a table + * This method is automatically called in Phalcon\Db\Adapter\Pdo + * constructor. Call it when you need to restore a database connection. * - * - * print_r( - * $connection->describeColumns("posts") - * ); - * - * - * @param string $table - * @param string $schema - * @return \Phalcon\Db\ColumnInterface[] + * @param array $descriptor + * @return bool */ - public function describeColumns($table, $schema = null) {} + public function connect(array $descriptor = null): bool {} /** * Creates a table @@ -62,30 +56,42 @@ public function describeColumns($table, $schema = null) {} * @param array $definition * @return bool */ - public function createTable($tableName, $schemaName, array $definition) {} + public function createTable(string $tableName, string $schemaName, array $definition): bool {} /** - * Modifies a table column based on a definition + * Returns an array of Phalcon\Db\Column objects describing a table * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn - * @return bool + * ```php + * print_r( + * $connection->describeColumns("posts") + * ); + * ``` + * + * @param string $table + * @param string $schema + * @return array|\Phalcon\Db\ColumnInterface[] */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null) {} + public function describeColumns(string $table, string $schema = null): array {} /** - * Check whether the database system requires an explicit value for identity columns + * Lists table references * - * @return bool + * ```php + * print_r( + * $connection->describeReferences("robots_parts") + * ); + * ``` + * + * @param string $table + * @param string $schema + * @return array|\Phalcon\Db\ReferenceInterface[] */ - public function useExplicitIdValue() {} + public function describeReferences(string $table, string $schema = null): array {} /** * Returns the default identity value to be inserted in an identity column * - * + * ```php * // Inserting a new robot with a valid default value for the column 'id' * $success = $connection->insert( * "robots", @@ -100,17 +106,44 @@ public function useExplicitIdValue() {} * "year", * ] * ); - * + * ``` * * @return \Phalcon\Db\RawValue */ - public function getDefaultIdValue() {} + public function getDefaultIdValue(): RawValue {} /** - * Check whether the database system requires a sequence to produce auto-numeric values + * Modifies a table column based on a definition * + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return bool */ - public function supportSequences() {} + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): bool {} + + /** + * Check whether the database system requires a sequence to produce + * auto-numeric values + * + * @return bool + */ + public function supportSequences(): bool {} + + /** + * Check whether the database system requires an explicit value for identity + * columns + * + * @return bool + */ + public function useExplicitIdValue(): bool {} + + /** + * Returns PDO adapter DSN defaults as a key-value map. + * + * @return array + */ + protected function getDsnDefaults(): array {} } diff --git a/src/Phalcon/db/adapter/pdo/Sqlite.php b/src/Phalcon/db/adapter/pdo/Sqlite.php index bcf551fa..8acf592d 100644 --- a/src/Phalcon/db/adapter/pdo/Sqlite.php +++ b/src/Phalcon/db/adapter/pdo/Sqlite.php @@ -3,11 +3,9 @@ namespace Phalcon\Db\Adapter\Pdo; /** - * Phalcon\Db\Adapter\Pdo\Sqlite - * * Specific functions for the Sqlite database system * - * + * ```php * use Phalcon\Db\Adapter\Pdo\Sqlite; * * $connection = new Sqlite( @@ -15,79 +13,81 @@ * "dbname" => "/tmp/test.sqlite", * ] * ); - * + * ``` */ -class Sqlite extends \Phalcon\Db\Adapter\Pdo +class Sqlite extends \Phalcon\Db\Adapter\Pdo\AbstractPdo { + /** + * @var string + */ + protected $dialectType = 'sqlite'; - protected $_type = 'sqlite'; - + /** + * @var string + */ + protected $type = 'sqlite'; - protected $_dialectType = 'sqlite'; + /** + * Constructor for Phalcon\Db\Adapter\Pdo\Sqlite + * + * @param array $descriptor + */ + public function __construct(array $descriptor) {} /** - * This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. - * Call it when you need to restore a database connection. + * This method is automatically called in Phalcon\Db\Adapter\Pdo + * constructor. Call it when you need to restore a database connection. * * @param array $descriptor * @return bool */ - public function connect(array $descriptor = null) {} + public function connect(array $descriptor = null): bool {} /** * Returns an array of Phalcon\Db\Column objects describing a table * - * + * ```php * print_r( * $connection->describeColumns("posts") * ); - * + * ``` * * @param string $table * @param string $schema - * @return \Phalcon\Db\ColumnInterface[] + * @return array|\Phalcon\Db\ColumnInterface[] */ - public function describeColumns($table, $schema = null) {} + public function describeColumns(string $table, string $schema = null): array {} /** * Lists table indexes * - * + * ```php * print_r( * $connection->describeIndexes("robots_parts") * ); - * + * ``` * * @param string $table * @param string $schema - * @return \Phalcon\Db\IndexInterface[] + * @return array|\Phalcon\Db\IndexInterface[] */ - public function describeIndexes($table, $schema = null) {} + public function describeIndexes(string $table, string $schema = null): array {} /** * Lists table references * - * @param string table - * @param string schema - * @return Phalcon\Db\ReferenceInterface[] * @param string $table * @param string $schema - * @return \Phalcon\Db\ReferenceInterface[] - */ - public function describeReferences($table, $schema = null) {} - - /** - * Check whether the database system requires an explicit value for identity columns - * - * @return bool + * @return array|\Phalcon\Db\ReferenceInterface[] */ - public function useExplicitIdValue() {} + public function describeReferences(string $table, string $schema = null): array {} /** - * Returns the default value to make the RBDM use the default value declared in the table definition + * Returns the default value to make the RBDM use the default value declared + * in the table definition * - * + * ```php * // Inserting a new robot with a valid default value for the column 'year' * $success = $connection->insert( * "robots", @@ -100,10 +100,25 @@ public function useExplicitIdValue() {} * "year", * ] * ); - * + * ``` * * @return \Phalcon\Db\RawValue */ - public function getDefaultValue() {} + public function getDefaultValue(): RawValue {} + + /** + * Check whether the database system requires an explicit value for identity + * columns + * + * @return bool + */ + public function useExplicitIdValue(): bool {} + + /** + * Returns PDO adapter DSN defaults as a key-value map. + * + * @return array + */ + protected function getDsnDefaults(): array {} } diff --git a/src/Phalcon/db/dialect/Mysql.php b/src/Phalcon/db/dialect/Mysql.php index 7f2170b0..85905487 100644 --- a/src/Phalcon/db/dialect/Mysql.php +++ b/src/Phalcon/db/dialect/Mysql.php @@ -3,23 +3,15 @@ namespace Phalcon\Db\Dialect; /** - * Phalcon\Db\Dialect\Mysql - * * Generates database specific SQL for the MySQL RDBMS */ class Mysql extends \Phalcon\Db\Dialect { - - protected $_escapeChar = '`'; - - /** - * Gets the column name in MySQL - * - * @param \Phalcon\Db\ColumnInterface $column - * @return string + * @var string */ - public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} + protected $escapeChar = '`'; + /** * Generates SQL to add a column to a table @@ -29,77 +21,100 @@ public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function addColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column) {} + public function addColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL to modify a column in a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn + * @param \Phalcon\Db\ReferenceInterface $reference * @return string */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null) {} + public function addForeignKey(string $tableName, string $schemaName, \Phalcon\Db\ReferenceInterface $reference): string {} /** - * Generates SQL to delete a column from a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param string $columnName + * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function dropColumn($tableName, $schemaName, $columnName) {} + public function addIndex(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to add the primary key to a table * * @param string $tableName * @param string $schemaName * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addIndex($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function addPrimaryKey(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to delete an index from a table + * Generates SQL to create a table * * @param string $tableName * @param string $schemaName - * @param string $indexName + * @param array $definition * @return string */ - public function dropIndex($tableName, $schemaName, $indexName) {} + public function createTable(string $tableName, string $schemaName, array $definition): string {} /** - * Generates SQL to add the primary key to a table + * Generates SQL to create a view * - * @param string $tableName + * @param string $viewName + * @param array $definition * @param string $schemaName - * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addPrimaryKey($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function createView(string $viewName, array $definition, string $schemaName = null): string {} /** - * Generates SQL to delete primary key from a table + * Generates SQL describing a table * - * @param string $tableName - * @param string $schemaName + * ```php + * print_r( + * $dialect->describeColumns("posts") + * ); + * ``` + * + * @param string $table + * @param string $schema * @return string */ - public function dropPrimaryKey($tableName, $schemaName) {} + public function describeColumns(string $table, string $schema = null): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to query indexes on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeIndexes(string $table, string $schema = null): string {} + + /** + * Generates SQL to query foreign keys on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeReferences(string $table, string $schema = null): string {} + + /** + * Generates SQL to delete a column from a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\ReferenceInterface $reference + * @param string $columnName * @return string */ - public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInterface $reference) {} + public function dropColumn(string $tableName, string $schemaName, string $columnName): string {} /** * Generates SQL to delete a foreign key from a table @@ -109,26 +124,26 @@ public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInte * @param string $referenceName * @return string */ - public function dropForeignKey($tableName, $schemaName, $referenceName) {} + public function dropForeignKey(string $tableName, string $schemaName, string $referenceName): string {} /** - * Generates SQL to create a table + * Generates SQL to delete an index from a table * * @param string $tableName * @param string $schemaName - * @param array $definition + * @param string $indexName * @return string */ - public function createTable($tableName, $schemaName, array $definition) {} + public function dropIndex(string $tableName, string $schemaName, string $indexName): string {} /** - * Generates SQL to truncate a table + * Generates SQL to delete primary key from a table * * @param string $tableName * @param string $schemaName * @return string */ - public function truncateTable($tableName, $schemaName) {} + public function dropPrimaryKey(string $tableName, string $schemaName): string {} /** * Generates SQL to drop a table @@ -138,115 +153,121 @@ public function truncateTable($tableName, $schemaName) {} * @param bool $ifExists * @return string */ - public function dropTable($tableName, $schemaName = null, $ifExists = true) {} + public function dropTable(string $tableName, string $schemaName = null, bool $ifExists = true): string {} /** - * Generates SQL to create a view + * Generates SQL to drop a view * * @param string $viewName - * @param array $definition * @param string $schemaName + * @param bool $ifExists * @return string */ - public function createView($viewName, array $definition, $schemaName = null) {} + public function dropView(string $viewName, string $schemaName = null, bool $ifExists = true): string {} /** - * Generates SQL to drop a view + * Gets the column name in MySQL * - * @param string $viewName - * @param string $schemaName - * @param bool $ifExists + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function dropView($viewName, $schemaName = null, $ifExists = true) {} + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL checking for the existence of a schema.table + * Generates SQL to check DB parameter FOREIGN_KEY_CHECKS. * - * - * echo $dialect->tableExists("posts", "blog"); + * @return string + */ + public function getForeignKeyChecks(): string {} + + /** + * List all tables in database * - * echo $dialect->tableExists("posts"); - * + * ```php + * print_r( + * $dialect->listTables("blog") + * ); + * ``` * - * @param string $tableName * @param string $schemaName * @return string */ - public function tableExists($tableName, $schemaName = null) {} + public function listTables(string $schemaName = null): string {} /** - * Generates SQL checking for the existence of a schema.view + * Generates the SQL to list all views of a schema or user * - * @param string $viewName * @param string $schemaName * @return string */ - public function viewExists($viewName, $schemaName = null) {} + public function listViews(string $schemaName = null): string {} /** - * Generates SQL describing a table - * - * - * print_r( - * $dialect->describeColumns("posts") - * ); - * + * Generates SQL to modify a column in a table * - * @param string $table - * @param string $schema + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return string */ - public function describeColumns($table, $schema = null) {} + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): string {} /** - * List all tables in database + * Returns a SQL modified with a LOCK IN SHARE MODE clause * - * - * print_r( - * $dialect->listTables("blog") - * ); - * + * ```php + * $sql = $dialect->sharedLock("SELECT FROM robots"); * - * @param string $schemaName + * echo $sql; // SELECT FROM robots LOCK IN SHARE MODE + * ``` + * + * @param string $sqlQuery * @return string */ - public function listTables($schemaName = null) {} + public function sharedLock(string $sqlQuery): string {} /** - * Generates the SQL to list all views of a schema or user + * Generates SQL checking for the existence of a schema.table + * + * ```php + * echo $dialect->tableExists("posts", "blog"); + * + * echo $dialect->tableExists("posts"); + * ``` * + * @param string $tableName * @param string $schemaName * @return string */ - public function listViews($schemaName = null) {} + public function tableExists(string $tableName, string $schemaName = null): string {} /** - * Generates SQL to query indexes on a table + * Generates the SQL to describe the table creation options * * @param string $table * @param string $schema * @return string */ - public function describeIndexes($table, $schema = null) {} + public function tableOptions(string $table, string $schema = null): string {} /** - * Generates SQL to query foreign keys on a table + * Generates SQL to truncate a table * - * @param string $table - * @param string $schema + * @param string $tableName + * @param string $schemaName * @return string */ - public function describeReferences($table, $schema = null) {} + public function truncateTable(string $tableName, string $schemaName): string {} /** - * Generates the SQL to describe the table creation options + * Generates SQL checking for the existence of a schema.view * - * @param string $table - * @param string $schema + * @param string $viewName + * @param string $schemaName * @return string */ - public function tableOptions($table, $schema = null) {} + public function viewExists(string $viewName, string $schemaName = null): string {} /** * Generates SQL to add the table creation options @@ -254,26 +275,23 @@ public function tableOptions($table, $schema = null) {} * @param array $definition * @return string */ - protected function _getTableOptions(array $definition) {} + protected function getTableOptions(array $definition): string {} /** - * Generates SQL to check DB parameter FOREIGN_KEY_CHECKS. + * Checks if the size and/or scale are present and encloses those values + * in parentheses if need be * + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function getForeignKeyChecks() {} + private function checkColumnSizeAndScale(\Phalcon\Db\ColumnInterface $column): string {} /** - * Returns a SQL modified with a LOCK IN SHARE MODE clause - * - * - * $sql = $dialect->sharedLock("SELECT FROM robots"); - * echo $sql; // SELECT FROM robots LOCK IN SHARE MODE - * + * Checks if a column is unsigned or not and returns the relevant SQL syntax * - * @param string $sqlQuery + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function sharedLock($sqlQuery) {} + private function checkColumnUnsigned(\Phalcon\Db\ColumnInterface $column): string {} } diff --git a/src/Phalcon/db/dialect/Postgresql.php b/src/Phalcon/db/dialect/Postgresql.php index ff800073..2ef5c5ff 100644 --- a/src/Phalcon/db/dialect/Postgresql.php +++ b/src/Phalcon/db/dialect/Postgresql.php @@ -3,23 +3,15 @@ namespace Phalcon\Db\Dialect; /** - * Phalcon\Db\Dialect\Postgresql - * * Generates database specific SQL for the PostgreSQL RDBMS */ class Postgresql extends \Phalcon\Db\Dialect { - - protected $_escapeChar = '\\\"'; - - /** - * Gets the column name in PostgreSQL - * - * @param \Phalcon\Db\ColumnInterface $column - * @return string + * @var string */ - public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} + protected $escapeChar = '\\\"'; + /** * Generates SQL to add a column to a table @@ -29,77 +21,100 @@ public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function addColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column) {} + public function addColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL to modify a column in a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn + * @param \Phalcon\Db\ReferenceInterface $reference * @return string */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null) {} + public function addForeignKey(string $tableName, string $schemaName, \Phalcon\Db\ReferenceInterface $reference): string {} /** - * Generates SQL to delete a column from a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param string $columnName + * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function dropColumn($tableName, $schemaName, $columnName) {} + public function addIndex(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to add the primary key to a table * * @param string $tableName * @param string $schemaName * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addIndex($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function addPrimaryKey(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to delete an index from a table + * Generates SQL to create a table * * @param string $tableName * @param string $schemaName - * @param string $indexName + * @param array $definition * @return string */ - public function dropIndex($tableName, $schemaName, $indexName) {} + public function createTable(string $tableName, string $schemaName, array $definition): string {} /** - * Generates SQL to add the primary key to a table + * Generates SQL to create a view * - * @param string $tableName + * @param string $viewName + * @param array $definition * @param string $schemaName - * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addPrimaryKey($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function createView(string $viewName, array $definition, string $schemaName = null): string {} /** - * Generates SQL to delete primary key from a table + * Generates SQL describing a table * - * @param string $tableName - * @param string $schemaName + * ```php + * print_r( + * $dialect->describeColumns("posts") + * ); + * ``` + * + * @param string $table + * @param string $schema * @return string */ - public function dropPrimaryKey($tableName, $schemaName) {} + public function describeColumns(string $table, string $schema = null): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to query indexes on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeIndexes(string $table, string $schema = null): string {} + + /** + * Generates SQL to query foreign keys on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeReferences(string $table, string $schema = null): string {} + + /** + * Generates SQL to delete a column from a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\ReferenceInterface $reference + * @param string $columnName * @return string */ - public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInterface $reference) {} + public function dropColumn(string $tableName, string $schemaName, string $columnName): string {} /** * Generates SQL to delete a foreign key from a table @@ -109,26 +124,26 @@ public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInte * @param string $referenceName * @return string */ - public function dropForeignKey($tableName, $schemaName, $referenceName) {} + public function dropForeignKey(string $tableName, string $schemaName, string $referenceName): string {} /** - * Generates SQL to create a table + * Generates SQL to delete an index from a table * * @param string $tableName * @param string $schemaName - * @param array $definition - * @return string|array + * @param string $indexName + * @return string */ - public function createTable($tableName, $schemaName, array $definition) {} + public function dropIndex(string $tableName, string $schemaName, string $indexName): string {} /** - * Generates SQL to truncate a table + * Generates SQL to delete primary key from a table * * @param string $tableName * @param string $schemaName * @return string */ - public function truncateTable($tableName, $schemaName) {} + public function dropPrimaryKey(string $tableName, string $schemaName): string {} /** * Generates SQL to drop a table @@ -138,135 +153,120 @@ public function truncateTable($tableName, $schemaName) {} * @param bool $ifExists * @return string */ - public function dropTable($tableName, $schemaName = null, $ifExists = true) {} + public function dropTable(string $tableName, string $schemaName = null, bool $ifExists = true): string {} /** - * Generates SQL to create a view + * Generates SQL to drop a view * * @param string $viewName - * @param array $definition * @param string $schemaName + * @param bool $ifExists * @return string */ - public function createView($viewName, array $definition, $schemaName = null) {} + public function dropView(string $viewName, string $schemaName = null, bool $ifExists = true): string {} /** - * Generates SQL to drop a view + * Gets the column name in PostgreSQL * - * @param string $viewName - * @param string $schemaName - * @param bool $ifExists + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function dropView($viewName, $schemaName = null, $ifExists = true) {} + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL checking for the existence of a schema.table - * - * - * echo $dialect->tableExists("posts", "blog"); + * List all tables in database * - * echo $dialect->tableExists("posts"); - * + * ```php + * print_r( + * $dialect->listTables("blog") + * ); + * ``` * - * @param string $tableName * @param string $schemaName * @return string */ - public function tableExists($tableName, $schemaName = null) {} + public function listTables(string $schemaName = null): string {} /** - * Generates SQL checking for the existence of a schema.view + * Generates the SQL to list all views of a schema or user * - * @param string $viewName * @param string $schemaName * @return string */ - public function viewExists($viewName, $schemaName = null) {} + public function listViews(string $schemaName = null): string {} /** - * Generates SQL describing a table - * - * - * print_r( - * $dialect->describeColumns("posts") - * ); - * + * Generates SQL to modify a column in a table * - * @param string $table - * @param string $schema + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return string */ - public function describeColumns($table, $schema = null) {} + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): string {} /** - * List all tables in database - * - * - * print_r( - * $dialect->listTables("blog") - * ); - * + * Returns a SQL modified a shared lock statement. For now this method + * returns the original query * - * @param string $schemaName + * @param string $sqlQuery * @return string */ - public function listTables($schemaName = null) {} + public function sharedLock(string $sqlQuery): string {} /** - * Generates the SQL to list all views of a schema or user + * Generates SQL checking for the existence of a schema.table + * + * ```php + * echo $dialect->tableExists("posts", "blog"); * + * echo $dialect->tableExists("posts"); + * ``` + * + * @param string $tableName * @param string $schemaName * @return string */ - public function listViews($schemaName = null) {} + public function tableExists(string $tableName, string $schemaName = null): string {} /** - * Generates SQL to query indexes on a table + * Generates the SQL to describe the table creation options * * @param string $table * @param string $schema * @return string */ - public function describeIndexes($table, $schema = null) {} + public function tableOptions(string $table, string $schema = null): string {} /** - * Generates SQL to query foreign keys on a table + * Generates SQL to truncate a table * - * @param string $table - * @param string $schema + * @param string $tableName + * @param string $schemaName * @return string */ - public function describeReferences($table, $schema = null) {} + public function truncateTable(string $tableName, string $schemaName): string {} /** - * Generates the SQL to describe the table creation options + * Generates SQL checking for the existence of a schema.view * - * @param string $table - * @param string $schema + * @param string $viewName + * @param string $schemaName * @return string */ - public function tableOptions($table, $schema = null) {} + public function viewExists(string $viewName, string $schemaName = null): string {} /** * @param \Phalcon\Db\ColumnInterface $column * @return string */ - protected function _castDefault(\Phalcon\Db\ColumnInterface $column) {} + protected function castDefault(\Phalcon\Db\ColumnInterface $column): string {} /** * @param array $definition * @return string */ - protected function _getTableOptions(array $definition) {} - - /** - * Returns a SQL modified a shared lock statement. For now this method - * returns the original query - * - * @param string $sqlQuery - * @return string - */ - public function sharedLock($sqlQuery) {} + protected function getTableOptions(array $definition): string {} } diff --git a/src/Phalcon/db/dialect/Sqlite.php b/src/Phalcon/db/dialect/Sqlite.php index f71e0ab8..f00fed05 100644 --- a/src/Phalcon/db/dialect/Sqlite.php +++ b/src/Phalcon/db/dialect/Sqlite.php @@ -3,23 +3,15 @@ namespace Phalcon\Db\Dialect; /** - * Phalcon\Db\Dialect\Sqlite - * - * Generates database specific SQL for the Sqlite RDBMS + * Generates database specific SQL for the SQLite RDBMS */ class Sqlite extends \Phalcon\Db\Dialect { - - protected $_escapeChar = '\\\"'; - - /** - * Gets the column name in SQLite - * - * @param \Phalcon\Db\ColumnInterface $column - * @return string + * @var string */ - public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} + protected $escapeChar = '\\\"'; + /** * Generates SQL to add a column to a table @@ -29,126 +21,147 @@ public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column) {} * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function addColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column) {} + public function addColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL to modify a column in a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param \Phalcon\Db\ColumnInterface $column - * @param \Phalcon\Db\ColumnInterface $currentColumn + * @param \Phalcon\Db\ReferenceInterface $reference * @return string */ - public function modifyColumn($tableName, $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null) {} + public function addForeignKey(string $tableName, string $schemaName, \Phalcon\Db\ReferenceInterface $reference): string {} /** - * Generates SQL to delete a column from a table + * Generates SQL to add an index to a table * * @param string $tableName * @param string $schemaName - * @param string $columnName + * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function dropColumn($tableName, $schemaName, $columnName) {} + public function addIndex(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to add the primary key to a table * * @param string $tableName * @param string $schemaName * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addIndex($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function addPrimaryKey(string $tableName, string $schemaName, \Phalcon\Db\IndexInterface $index): string {} /** - * Generates SQL to delete an index from a table + * Generates SQL to create a table * * @param string $tableName * @param string $schemaName - * @param string $indexName + * @param array $definition * @return string */ - public function dropIndex($tableName, $schemaName, $indexName) {} + public function createTable(string $tableName, string $schemaName, array $definition): string {} /** - * Generates SQL to add the primary key to a table + * Generates SQL to create a view * - * @param string $tableName + * @param string $viewName + * @param array $definition * @param string $schemaName - * @param \Phalcon\Db\IndexInterface $index * @return string */ - public function addPrimaryKey($tableName, $schemaName, \Phalcon\Db\IndexInterface $index) {} + public function createView(string $viewName, array $definition, string $schemaName = null): string {} /** - * Generates SQL to delete primary key from a table + * Generates SQL describing a table * - * @param string $tableName - * @param string $schemaName + * ```php + * print_r( + * $dialect->describeColumns("posts") + * ); + * ``` + * + * @param string $table + * @param string $schema * @return string */ - public function dropPrimaryKey($tableName, $schemaName) {} + public function describeColumns(string $table, string $schema = null): string {} /** - * Generates SQL to add an index to a table + * Generates SQL to query indexes detail on a table * - * @param string $tableName - * @param string $schemaName - * @param \Phalcon\Db\ReferenceInterface $reference + * @param string $index * @return string */ - public function addForeignKey($tableName, $schemaName, \Phalcon\Db\ReferenceInterface $reference) {} + public function describeIndex(string $index): string {} /** - * Generates SQL to delete a foreign key from a table + * Generates SQL to query indexes on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeIndexes(string $table, string $schema = null): string {} + + /** + * Generates SQL to query foreign keys on a table + * + * @param string $table + * @param string $schema + * @return string + */ + public function describeReferences(string $table, string $schema = null): string {} + + /** + * Generates SQL to delete a column from a table * * @param string $tableName * @param string $schemaName - * @param string $referenceName + * @param string $columnName * @return string */ - public function dropForeignKey($tableName, $schemaName, $referenceName) {} + public function dropColumn(string $tableName, string $schemaName, string $columnName): string {} /** - * Generates SQL to create a table + * Generates SQL to delete a foreign key from a table * * @param string $tableName * @param string $schemaName - * @param array $definition + * @param string $referenceName * @return string */ - public function createTable($tableName, $schemaName, array $definition) {} + public function dropForeignKey(string $tableName, string $schemaName, string $referenceName): string {} /** - * Generates SQL to truncate a table + * Generates SQL to delete an index from a table * * @param string $tableName * @param string $schemaName + * @param string $indexName * @return string */ - public function truncateTable($tableName, $schemaName) {} + public function dropIndex(string $tableName, string $schemaName, string $indexName): string {} /** - * Generates SQL to drop a table + * Generates SQL to delete primary key from a table * * @param string $tableName * @param string $schemaName - * @param bool $ifExists * @return string */ - public function dropTable($tableName, $schemaName = null, $ifExists = true) {} + public function dropPrimaryKey(string $tableName, string $schemaName): string {} /** - * Generates SQL to create a view + * Generates SQL to drop a table * - * @param string $viewName - * @param array $definition + * @param string $tableName * @param string $schemaName + * @param bool $ifExists * @return string */ - public function createView($viewName, array $definition, $schemaName = null) {} + public function dropTable(string $tableName, string $schemaName = null, bool $ifExists = true): string {} /** * Generates SQL to drop a view @@ -158,60 +171,54 @@ public function createView($viewName, array $definition, $schemaName = null) {} * @param bool $ifExists * @return string */ - public function dropView($viewName, $schemaName = null, $ifExists = true) {} + public function dropView(string $viewName, string $schemaName = null, bool $ifExists = true): string {} /** - * Generates SQL checking for the existence of a schema.table + * Returns a SQL modified with a FOR UPDATE clause. For SQLite it returns + * the original query * - * - * echo $dialect->tableExists("posts", "blog"); - * - * echo $dialect->tableExists("posts"); - * - * - * @param string $tableName - * @param string $schemaName + * @param string $sqlQuery * @return string */ - public function tableExists($tableName, $schemaName = null) {} + public function forUpdate(string $sqlQuery): string {} /** - * Generates SQL checking for the existence of a schema.view + * Gets the column name in SQLite * - * @param string $viewName - * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column * @return string */ - public function viewExists($viewName, $schemaName = null) {} + public function getColumnDefinition(\Phalcon\Db\ColumnInterface $column): string {} /** - * Generates SQL describing a table + * Generates the SQL to get query list of indexes * - * + * ```php * print_r( - * $dialect->describeColumns("posts") + * $dialect->listIndexesSql("blog") * ); - * + * ``` * * @param string $table * @param string $schema + * @param string $keyName * @return string */ - public function describeColumns($table, $schema = null) {} + public function listIndexesSql(string $table, string $schema = null, string $keyName = null): string {} /** * List all tables in database * - * + * ```php * print_r( * $dialect->listTables("blog") * ); - * + * ``` * * @param string $schemaName * @return string */ - public function listTables($schemaName = null) {} + public function listTables(string $schemaName = null): string {} /** * Generates the SQL to list all views of a schema or user @@ -219,66 +226,68 @@ public function listTables($schemaName = null) {} * @param string $schemaName * @return string */ - public function listViews($schemaName = null) {} + public function listViews(string $schemaName = null): string {} /** - * Generates the SQL to get query list of indexes - * - * - * print_r( - * $dialect->listIndexesSql("blog") - * ); - * + * Generates SQL to modify a column in a table * - * @param string $table - * @param string $schema - * @param string $keyName + * @param string $tableName + * @param string $schemaName + * @param \Phalcon\Db\ColumnInterface $column + * @param \Phalcon\Db\ColumnInterface $currentColumn * @return string */ - public function listIndexesSql($table, $schema = null, $keyName = null) {} + public function modifyColumn(string $tableName, string $schemaName, \Phalcon\Db\ColumnInterface $column, \Phalcon\Db\ColumnInterface $currentColumn = null): string {} /** - * Generates SQL to query indexes on a table + * Returns a SQL modified a shared lock statement. For now this method + * returns the original query * - * @param string $table - * @param string $schema + * @param string $sqlQuery * @return string */ - public function describeIndexes($table, $schema = null) {} + public function sharedLock(string $sqlQuery): string {} /** - * Generates SQL to query indexes detail on a table + * Generates SQL checking for the existence of a schema.table * - * @param string $index + * ```php + * echo $dialect->tableExists("posts", "blog"); + * + * echo $dialect->tableExists("posts"); + * ``` + * + * @param string $tableName + * @param string $schemaName * @return string */ - public function describeIndex($index) {} + public function tableExists(string $tableName, string $schemaName = null): string {} /** - * Generates SQL to query foreign keys on a table + * Generates the SQL to describe the table creation options * * @param string $table * @param string $schema * @return string */ - public function describeReferences($table, $schema = null) {} + public function tableOptions(string $table, string $schema = null): string {} /** - * Generates the SQL to describe the table creation options + * Generates SQL to truncate a table * - * @param string $table - * @param string $schema + * @param string $tableName + * @param string $schemaName * @return string */ - public function tableOptions($table, $schema = null) {} + public function truncateTable(string $tableName, string $schemaName): string {} /** - * Returns a SQL modified a shared lock statement. For now this method - * returns the original query + * Generates SQL checking for the existence of a schema.view * - * @param string $sqlQuery + * @param string $viewName + * @param string $schemaName * @return string */ - public function sharedLock($sqlQuery) {} + public function viewExists(string $viewName, string $schemaName = null): string {} } diff --git a/src/Phalcon/db/profiler/Item.php b/src/Phalcon/db/profiler/Item.php index 80149305..8e0bce9e 100644 --- a/src/Phalcon/db/profiler/Item.php +++ b/src/Phalcon/db/profiler/Item.php @@ -3,75 +3,73 @@ namespace Phalcon\Db\Profiler; /** - * Phalcon\Db\Profiler\Item - * * This class identifies each profile in a Phalcon\Db\Profiler */ class Item { /** - * SQL statement related to the profile + * Timestamp when the profile ended * - * @var string + * @var double */ - protected $_sqlStatement; + protected $finalTime; /** - * SQL variables related to the profile + * Timestamp when the profile started * - * @var array + * @var double */ - protected $_sqlVariables; + protected $initialTime; /** * SQL bind types related to the profile * * @var array */ - protected $_sqlBindTypes; + protected $sqlBindTypes; /** - * Timestamp when the profile started + * SQL statement related to the profile * - * @var double + * @var string */ - protected $_initialTime; + protected $sqlStatement; /** - * Timestamp when the profile ended + * SQL variables related to the profile * - * @var double + * @var array */ - protected $_finalTime; + protected $sqlVariables; /** - * SQL statement related to the profile + * Timestamp when the profile ended * - * @param string $sqlStatement + * @param double $finalTime */ - public function setSqlStatement($sqlStatement) {} + public function setFinalTime(float $finalTime) {} /** - * SQL statement related to the profile + * Timestamp when the profile ended * - * @return string + * @return double */ - public function getSqlStatement() {} + public function getFinalTime(): float {} /** - * SQL variables related to the profile + * Timestamp when the profile started * - * @param array $sqlVariables + * @param double $initialTime */ - public function setSqlVariables(array $sqlVariables) {} + public function setInitialTime(float $initialTime) {} /** - * SQL variables related to the profile + * Timestamp when the profile started * - * @return array + * @return double */ - public function getSqlVariables() {} + public function getInitialTime(): float {} /** * SQL bind types related to the profile @@ -85,41 +83,41 @@ public function setSqlBindTypes(array $sqlBindTypes) {} * * @return array */ - public function getSqlBindTypes() {} + public function getSqlBindTypes(): array {} /** - * Timestamp when the profile started + * SQL statement related to the profile * - * @param double $initialTime + * @param string $sqlStatement */ - public function setInitialTime($initialTime) {} + public function setSqlStatement(string $sqlStatement) {} /** - * Timestamp when the profile started + * SQL statement related to the profile * - * @return double + * @return string */ - public function getInitialTime() {} + public function getSqlStatement(): string {} /** - * Timestamp when the profile ended + * SQL variables related to the profile * - * @param double $finalTime + * @param array $sqlVariables */ - public function setFinalTime($finalTime) {} + public function setSqlVariables(array $sqlVariables) {} /** - * Timestamp when the profile ended + * SQL variables related to the profile * - * @return double + * @return array */ - public function getFinalTime() {} + public function getSqlVariables(): array {} /** * Returns the total time in seconds spent by the profile * * @return double */ - public function getTotalElapsedSeconds() {} + public function getTotalElapsedSeconds(): float {} } diff --git a/src/Phalcon/db/result/Pdo.php b/src/Phalcon/db/result/Pdo.php index b7d9bdfa..42675919 100644 --- a/src/Phalcon/db/result/Pdo.php +++ b/src/Phalcon/db/result/Pdo.php @@ -3,89 +3,109 @@ namespace Phalcon\Db\Result; /** - * Phalcon\Db\Result\Pdo - * * Encapsulates the resultset internals * - * + * ```php * $result = $connection->query("SELECT FROM robots ORDER BY name"); * * $result->setFetchMode( - * \Phalcon\Db::FETCH_NUM + * \Phalcon\Db\Enum::FETCH_NUM * ); * * while ($robot = $result->fetchArray()) { * print_r($robot); * } - * + * ``` */ class Pdo implements \Phalcon\Db\ResultInterface { - protected $_connection; + protected $bindParams; + + + protected $bindTypes; - protected $_result; + protected $connection; /** * Active fetch mode */ - protected $_fetchMode = Db::FETCH_OBJ; + protected $fetchMode = Enum::FETCH_OBJ; /** * Internal resultset * * @var \PDOStatement */ - protected $_pdoStatement; - - - protected $_sqlStatement; + protected $pdoStatement; - protected $_bindParams; + protected $result; - protected $_bindTypes; + protected $rowCount = false; - protected $_rowCount = false; + protected $sqlStatement; /** * Phalcon\Db\Result\Pdo constructor * - * @param \Phalcon\Db\AdapterInterface $connection + * @param Db\AdapterInterface $connection * @param \PDOStatement $result - * @param string $sqlStatement - * @param array $bindParams - * @param array $bindTypes + * @param mixed $sqlStatement + * @param mixed $bindParams + * @param mixed $bindTypes */ public function __construct(Db\AdapterInterface $connection, \PDOStatement $result, $sqlStatement = null, $bindParams = null, $bindTypes = null) {} /** - * Allows to execute the statement again. Some database systems don't support scrollable cursors, - * So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining + * Moves internal resultset cursor to another position letting us to fetch a + * certain row + * + * ```php + * $result = $connection->query( + * "SELECT FROM robots ORDER BY name" + * ); + * + * // Move to third row on result + * $result->dataSeek(2); + * + * // Fetch third row + * $row = $result->fetch(); + * ``` + * + * @param long $number + */ + public function dataSeek(int $number) {} + + /** + * Allows to execute the statement again. Some database systems don't + * support scrollable cursors. So, as cursors are forward only, we need to + * execute the cursor again to fetch rows from the begining * * @return bool */ - public function execute() {} + public function execute(): bool {} /** - * Fetches an array/object of strings that corresponds to the fetched row, or FALSE if there are no more rows. - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode + * Fetches an array/object of strings that corresponds to the fetched row, + * or FALSE if there are no more rows. This method is affected by the active + * fetch flag set using `Phalcon\Db\Result\Pdo::setFetchMode()` * - * + * ```php * $result = $connection->query("SELECT FROM robots ORDER BY name"); * * $result->setFetchMode( - * \Phalcon\Db::FETCH_OBJ + * \Phalcon\Enum::FETCH_OBJ * ); * * while ($robot = $result->fetch()) { * echo $robot->name; * } - * + * ``` * * @param mixed $fetchStyle * @param mixed $cursorOrientation @@ -93,114 +113,97 @@ public function execute() {} */ public function fetch($fetchStyle = null, $cursorOrientation = null, $cursorOffset = null) {} - /** - * Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode - * - * - * $result = $connection->query("SELECT FROM robots ORDER BY name"); - * - * $result->setFetchMode( - * \Phalcon\Db::FETCH_NUM - * ); - * - * while ($robot = result->fetchArray()) { - * print_r($robot); - * } - * - */ - public function fetchArray() {} - /** * Returns an array of arrays containing all the records in the result - * This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode + * This method is affected by the active fetch flag set using + * `Phalcon\Db\Result\Pdo::setFetchMode()` * - * + * ```php * $result = $connection->query( * "SELECT FROM robots ORDER BY name" * ); * * $robots = $result->fetchAll(); - * + * ``` * * @param mixed $fetchStyle * @param mixed $fetchArgument * @param mixed $ctorArgs * @return array */ - public function fetchAll($fetchStyle = null, $fetchArgument = null, $ctorArgs = null) {} + public function fetchAll($fetchStyle = null, $fetchArgument = null, $ctorArgs = null): array {} /** - * Gets number of rows returned by a resultset + * Returns an array of strings that corresponds to the fetched row, or FALSE + * if there are no more rows. This method is affected by the active fetch + * flag set using `Phalcon\Db\Result\Pdo::setFetchMode()` * - * - * $result = $connection->query( - * "SELECT FROM robots ORDER BY name" + * ```php + * $result = $connection->query("SELECT FROM robots ORDER BY name"); + * + * $result->setFetchMode( + * \Phalcon\Enum::FETCH_NUM * ); * - * echo "There are ", $result->numRows(), " rows in the resultset"; - * + * while ($robot = result->fetchArray()) { + * print_r($robot); + * } + * ``` + */ + public function fetchArray() {} + + /** + * Gets the internal PDO result object * - * @return int + * @return \PDOStatement */ - public function numRows() {} + public function getInternalResult(): \PDOStatement {} /** - * Moves internal resultset cursor to another position letting us to fetch a certain row + * Gets number of rows returned by a resultset * - * + * ```php * $result = $connection->query( * "SELECT FROM robots ORDER BY name" * ); * - * // Move to third row on result - * $result->dataSeek(2); - * - * // Fetch third row - * $row = $result->fetch(); - * + * echo "There are ", $result->numRows(), " rows in the resultset"; + * ``` * - * @param long $number + * @return int */ - public function dataSeek($number) {} + public function numRows(): int {} /** * Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch() * - * + * ```php * // Return array with integer indexes * $result->setFetchMode( - * \Phalcon\Db::FETCH_NUM + * \Phalcon\Enum::FETCH_NUM * ); * * // Return associative array without integer indexes * $result->setFetchMode( - * \Phalcon\Db::FETCH_ASSOC + * \Phalcon\Enum::FETCH_ASSOC * ); * * // Return associative array together with integer indexes * $result->setFetchMode( - * \Phalcon\Db::FETCH_BOTH + * \Phalcon\Enum::FETCH_BOTH * ); * * // Return an object * $result->setFetchMode( - * \Phalcon\Db::FETCH_OBJ + * \Phalcon\Enum::FETCH_OBJ * ); - * + * ``` * * @param int $fetchMode * @param mixed $colNoOrClassNameOrObject * @param mixed $ctorargs * @return bool */ - public function setFetchMode($fetchMode, $colNoOrClassNameOrObject = null, $ctorargs = null) {} - - /** - * Gets the internal PDO result object - * - * @return \PDOStatement - */ - public function getInternalResult() {} + public function setFetchMode(int $fetchMode, $colNoOrClassNameOrObject = null, $ctorargs = null): bool {} } diff --git a/src/Phalcon/debug/Dump.php b/src/Phalcon/debug/Dump.php index a1bc563f..96186819 100644 --- a/src/Phalcon/debug/Dump.php +++ b/src/Phalcon/debug/Dump.php @@ -3,68 +3,73 @@ namespace Phalcon\Debug; /** - * Phalcon\Debug\Dump - * * Dumps information about a variable(s) * - * + * ```php * $foo = 123; * * echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); - * + * ``` * - * + * ```php * $foo = "string"; * $bar = ["key" => "value"]; * $baz = new stdClass(); * * echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); - * + * ``` */ class Dump { + /** + * @var bool + */ + protected $detailed = false; - protected $_detailed = false; - - - protected $_methods = array(); - - - protected $_styles; + /** + * @var array + */ + protected $methods = array(); + /** + * @var array + */ + protected $styles = array(); - public function getDetailed() {} + /** + * @return bool + */ + public function getDetailed(): bool {} /** - * @param mixed $detailed + * @param bool $detailed */ - public function setDetailed($detailed) {} + public function setDetailed(bool $detailed) {} /** * Phalcon\Debug\Dump constructor * * @param array $styles - * @param boolean $detailed debug object's private and protected properties + * @param bool $detailed */ - public function __construct(array $styles = array(), $detailed = false) {} + public function __construct(array $styles = array(), bool $detailed = false) {} /** * Alias of variables() method * - * @param mixed $variable - * @param ... * @return string */ - public function all() {} + public function all(): string {} /** - * Get style for type + * Alias of variable() method * - * @param string $type + * @param mixed $variable + * @param string $name * @return string */ - protected function getStyle($type) {} + public function one($variable, string $name = null): string {} /** * Set styles for vars type @@ -72,77 +77,74 @@ protected function getStyle($type) {} * @param array $styles * @return array */ - public function setStyles(array $styles = array()) {} + public function setStyles(array $styles = array()): array {} /** - * Alias of variable() method + * Returns an JSON string of information about a single variable. * - * @param mixed $variable - * @param string $name - * @return string - */ - public function one($variable, $name = null) {} - - /** - * Prepare an HTML string of information about a single variable. + * ```php + * $foo = [ + * "key" => "value", + * ]; + * + * echo (new \Phalcon\Debug\Dump())->toJson($foo); + * + * $foo = new stdClass(); + * $foo->bar = "buz"; + * + * echo (new \Phalcon\Debug\Dump())->toJson($foo); + * ``` * * @param mixed $variable - * @param string $name - * @param int $tab * @return string */ - protected function output($variable, $name = null, $tab = 1) {} + public function toJson($variable): string {} /** * Returns an HTML string of information about a single variable. * - * + * ```php * echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); - * + * ``` * * @param mixed $variable * @param string $name * @return string */ - public function variable($variable, $name = null) {} + public function variable($variable, string $name = null): string {} /** * Returns an HTML string of debugging information about any number of * variables, each wrapped in a "pre" tag. * - * + * ```php * $foo = "string"; * $bar = ["key" => "value"]; * $baz = new stdClass(); * * echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); - * + * ``` * - * @param mixed $variable - * @param ... * @return string */ - public function variables() {} + public function variables(): string {} /** - * Returns an JSON string of information about a single variable. - * - * - * $foo = [ - * "key" => "value", - * ]; - * - * echo (new \Phalcon\Debug\Dump())->toJson($foo); - * - * $foo = new stdClass(); - * $foo->bar = "buz"; + * Get style for type * - * echo (new \Phalcon\Debug\Dump())->toJson($foo); - * + * @param string $type + * @return string + */ + protected function getStyle(string $type): string {} + + /** + * Prepare an HTML string of information about a single variable. * * @param mixed $variable + * @param string $name + * @param int $tab * @return string */ - public function toJson($variable) {} + protected function output($variable, string $name = null, int $tab = 1): string {} } diff --git a/src/Phalcon/debug/Exception.php b/src/Phalcon/debug/Exception.php index ea6c9862..9616f511 100644 --- a/src/Phalcon/debug/Exception.php +++ b/src/Phalcon/debug/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Debug; /** - * Phalcon\Debug\Exception - * * Exceptions thrown in Phalcon\Debug will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/DiInterface.php b/src/Phalcon/di/DiInterface.php similarity index 63% rename from src/Phalcon/DiInterface.php rename to src/Phalcon/di/DiInterface.php index a250d834..0e63ebd8 100644 --- a/src/Phalcon/DiInterface.php +++ b/src/Phalcon/di/DiInterface.php @@ -1,41 +1,13 @@ + * ```php * $service = new \Phalcon\Di\Service( * "request", - * "Phalcon\\Http\\Request" + * \Phalcon\Http\Request::class * ); * * $request = service->resolve(); - * + * ``` */ class Service implements \Phalcon\Di\ServiceInterface { - protected $_name; - - - protected $_definition; - - - protected $_shared = false; + protected $definition; + /** + * @var bool + */ + protected $resolved = false; - protected $_resolved = false; + /** + * @var bool + */ + protected $shared = false; - protected $_sharedInstance; + protected $sharedInstance; /** * Phalcon\Di\Service * - * @param string $name * @param mixed $definition - * @param boolean $shared + * @param bool $shared */ - public final function __construct($name, $definition, $shared = false) {} + final public function __construct($definition, bool $shared = false) {} /** - * Returns the service's name + * Returns the service definition * - * @return string + * @return mixed */ - public function getName() {} + public function getDefinition() {} /** - * Sets if the service is shared or not + * Returns a parameter in a specific position * - * @param bool $shared + * @param int $position + * @return array */ - public function setShared($shared) {} + public function getParameter(int $position) {} /** - * Check whether the service is shared or not + * Returns true if the service was resolved * * @return bool */ - public function isShared() {} - - /** - * Sets/Resets the shared instance related to the service - * - * @param mixed $sharedInstance - */ - public function setSharedInstance($sharedInstance) {} + public function isResolved(): bool {} /** - * Set the service definition + * Check whether the service is shared or not * - * @param mixed $definition + * @return bool */ - public function setDefinition($definition) {} + public function isShared(): bool {} /** - * Returns the service definition + * Resolves the service * + * @param array $parameters + * @param \Phalcon\Di\DiInterface $container * @return mixed */ - public function getDefinition() {} + public function resolve($parameters = null, \Phalcon\Di\DiInterface $container = null) {} /** - * Resolves the service + * Set the service definition * - * @param array $parameters - * @param \Phalcon\DiInterface $dependencyInjector - * @return mixed + * @param mixed $definition */ - public function resolve($parameters = null, \Phalcon\DiInterface $dependencyInjector = null) {} + public function setDefinition($definition) {} /** * Changes a parameter in the definition without resolve the service @@ -101,29 +93,20 @@ public function resolve($parameters = null, \Phalcon\DiInterface $dependencyInje * @param array $parameter * @return \Phalcon\Di\ServiceInterface */ - public function setParameter($position, array $parameter) {} - - /** - * Returns a parameter in a specific position - * - * @param int $position - * @return array - */ - public function getParameter($position) {} + public function setParameter(int $position, array $parameter): ServiceInterface {} /** - * Returns true if the service was resolved + * Sets if the service is shared or not * - * @return bool + * @param bool $shared */ - public function isResolved() {} + public function setShared(bool $shared) {} /** - * Restore the internal state of a service + * Sets/Resets the shared instance related to the service * - * @param array $attributes - * @return \Phalcon\Di\ServiceInterface + * @param mixed $sharedInstance */ - public static function __set_state(array $attributes) {} + public function setSharedInstance($sharedInstance) {} } diff --git a/src/Phalcon/di/ServiceInterface.php b/src/Phalcon/di/ServiceInterface.php index 9277779a..a7447ae8 100644 --- a/src/Phalcon/di/ServiceInterface.php +++ b/src/Phalcon/di/ServiceInterface.php @@ -3,56 +3,55 @@ namespace Phalcon\Di; /** - * Phalcon\Di\ServiceInterface - * * Represents a service in the services container */ interface ServiceInterface { /** - * Returns the service's name + * Returns the service definition * - * @param string + * @return mixed */ - public function getName(); + public function getDefinition(); /** - * Sets if the service is shared or not + * Returns a parameter in a specific position * - * @param bool $shared + * @param int $position + * @return array */ - public function setShared($shared); + public function getParameter(int $position); /** - * Check whether the service is shared or not + * Returns true if the service was resolved * * @return bool */ - public function isShared(); + public function isResolved(): bool; /** - * Set the service definition + * Check whether the service is shared or not * - * @param mixed $definition + * @return bool */ - public function setDefinition($definition); + public function isShared(): bool; /** - * Returns the service definition + * Resolves the service * + * @param array $parameters + * @param \Phalcon\Di\DiInterface $container * @return mixed */ - public function getDefinition(); + public function resolve($parameters = null, \Phalcon\Di\DiInterface $container = null); /** - * Resolves the service + * Set the service definition * - * @param array $parameters - * @param \Phalcon\DiInterface $dependencyInjector - * @return mixed + * @param mixed $definition */ - public function resolve($parameters = null, \Phalcon\DiInterface $dependencyInjector = null); + public function setDefinition($definition); /** * Changes a parameter in the definition without resolve the service @@ -61,14 +60,13 @@ public function resolve($parameters = null, \Phalcon\DiInterface $dependencyInje * @param array $parameter * @return ServiceInterface */ - public function setParameter($position, array $parameter); + public function setParameter(int $position, array $parameter): ServiceInterface; /** - * Restore the internal state of a service + * Sets if the service is shared or not * - * @param array $attributes - * @return ServiceInterface + * @param bool $shared */ - public static function __set_state(array $attributes); + public function setShared(bool $shared); } diff --git a/src/Phalcon/di/ServiceProviderInterface.php b/src/Phalcon/di/ServiceProviderInterface.php index 61c53270..e61eaedb 100644 --- a/src/Phalcon/di/ServiceProviderInterface.php +++ b/src/Phalcon/di/ServiceProviderInterface.php @@ -3,27 +3,28 @@ namespace Phalcon\Di; /** - * Phalcon\Di\ServiceProviderInterface + * Should be implemented by service providers, or such components, which + * register a service in the service container. * - * Should be implemented by service providers, or such components, - * which register a service in the service container. - * - * + * ```php * namespace Acme; * - * use Phalcon\DiInterface; + * use Phalcon\Di\DiInterface; * use Phalcon\Di\ServiceProviderInterface; * * class SomeServiceProvider implements ServiceProviderInterface * { * public function register(DiInterface $di) * { - * $di->setShared('service', function () { - * // ... - * }); + * $di->setShared( + * 'service', + * function () { + * // ... + * } + * ); * } * } - * + * ``` */ interface ServiceProviderInterface { @@ -31,8 +32,8 @@ interface ServiceProviderInterface /** * Registers a service provider. * - * @param \Phalcon\DiInterface $di + * @param \Phalcon\Di\DiInterface $di */ - public function register(\Phalcon\DiInterface $di); + public function register(\Phalcon\Di\DiInterface $di); } diff --git a/src/Phalcon/di/exception/ServiceResolutionException.php b/src/Phalcon/di/exception/ServiceResolutionException.php new file mode 100644 index 00000000..15c7d6b3 --- /dev/null +++ b/src/Phalcon/di/exception/ServiceResolutionException.php @@ -0,0 +1,11 @@ +false if an exception occurred and the operation was + * stopped by returning false in the exception handler. + * + * @throws \Exception if any uncaught or unhandled exception occurs during the dispatcher process. + * @return object|bool + */ + public function dispatch(): bool {} /** - * Sets the dependency injector + * Forwards the execution flow to another controller/action. * - * @param \Phalcon\DiInterface $dependencyInjector + * ```php + * $this->dispatcher->forward( + * [ + * "controller" => "posts", + * "action" => "index", + * ] + * ); + * ``` + * + * @throws \Phalcon\Exception + * @param array $forward */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function forward(array $forward) {} /** - * Returns the internal dependency injector + * Gets the latest dispatched action name * - * @return \Phalcon\DiInterface + * @return string */ - public function getDI() {} + public function getActionName(): string {} /** - * Sets the events manager + * Gets the default action suffix * - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @return string */ - public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + public function getActionSuffix(): string {} /** - * Returns the internal event manager + * Returns the current method to be/executed in the dispatcher * - * @return \Phalcon\Events\ManagerInterface + * @return string */ - public function getEventsManager() {} + public function getActiveMethod(): string {} /** - * Sets the default action suffix + * Returns bound models from binder instance * - * @param string $actionSuffix + * ```php + * class UserController extends Controller + * { + * public function showAction(User $user) + * { + * // return array with $user + * $boundModels = $this->dispatcher->getBoundModels(); + * } + * } + * ``` + * + * @return array */ - public function setActionSuffix($actionSuffix) {} + public function getBoundModels(): array {} /** - * Gets the default action suffix + * Returns the default namespace * * @return string */ - public function getActionSuffix() {} + public function getDefaultNamespace(): string {} /** - * Sets the module where the controller is (only informative) + * Returns the internal dependency injector * - * @param string $moduleName + * @return \Phalcon\Di\DiInterface */ - public function setModuleName($moduleName) {} + public function getDI(): DiInterface {} /** - * Gets the module where the controller class is + * Returns the internal event manager * - * @return string + * @return \Phalcon\Events\ManagerInterface */ - public function getModuleName() {} + public function getEventsManager(): ManagerInterface {} /** - * Sets the namespace where the controller class is + * Gets the default handler suffix * - * @param string $namespaceName + * @return string */ - public function setNamespaceName($namespaceName) {} + public function getHandlerSuffix(): string {} /** - * Gets a namespace to be prepended to the current handler name + * Gets model binder * - * @return string + * @return null|\Phalcon\Mvc\Model\BinderInterface */ - public function getNamespaceName() {} + public function getModelBinder(): ?BinderInterface {} /** - * Sets the default namespace + * Gets the module where the controller class is * - * @param string $namespaceName + * @return string */ - public function setDefaultNamespace($namespaceName) {} + public function getModuleName(): string {} /** - * Returns the default namespace + * Gets a namespace to be prepended to the current handler name * * @return string */ - public function getDefaultNamespace() {} + public function getNamespaceName(): string {} /** - * Sets the default action name + * Gets a param by its name or numeric index * - * @param string $actionName + * @param mixed $param + * @param string|array $filters + * @param mixed $defaultValue + * @return mixed */ - public function setDefaultAction($actionName) {} + public function getParam($param, $filters = null, $defaultValue = null) {} /** - * Sets the action name to be dispatched + * Gets action params * - * @param string $actionName + * @return array */ - public function setActionName($actionName) {} + public function getParams(): array {} /** - * Gets the latest dispatched action name + * Check if a param exists * - * @return string + * @param mixed $param + * @return bool */ - public function getActionName() {} + public function hasParam($param): bool {} /** - * Sets action params to be dispatched + * Checks if the dispatch loop is finished or has more pendent + * controllers/tasks to dispatch * - * @param array $params + * @return bool */ - public function setParams($params) {} + public function isFinished(): bool {} /** - * Gets action params + * Sets the action name to be dispatched * - * @return array + * @param string $actionName */ - public function getParams() {} + public function setActionName(string $actionName) {} /** - * Set a param by its name or numeric index + * Sets the default action name * - * @param mixed $param - * @param mixed $value + * @param string $actionName */ - public function setParam($param, $value) {} + public function setDefaultAction(string $actionName) {} /** - * Gets a param by its name or numeric index + * Sets the default namespace * - * @param mixed $param - * @param string|array $filters - * @param mixed $defaultValue - * @return mixed + * @param string $namespaceName */ - public function getParam($param, $filters = null, $defaultValue = null) {} + public function setDefaultNamespace(string $namespaceName) {} /** - * Check if a param exists + * Sets the dependency injector * - * @param mixed $param - * @return bool + * @param \Phalcon\Di\DiInterface $container */ - public function hasParam($param) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Returns the current method to be/executed in the dispatcher + * Possible class name that will be located to dispatch the request * * @return string */ - public function getActiveMethod() {} + public function getHandlerClass(): string {} /** - * Checks if the dispatch loop is finished or has more pendent controllers/tasks to dispatch + * Set a param by its name or numeric index * - * @return bool + * @param mixed $param + * @param mixed $value + */ + public function setParam($param, $value) {} + + /** + * Sets action params to be dispatched + * + * @param array $params */ - public function isFinished() {} + public function setParams(array $params) {} /** * Sets the latest returned value by an action manually @@ -265,130 +326,88 @@ public function isFinished() {} public function setReturnedValue($value) {} /** - * Returns value returned by the latest dispatched action + * Sets the default action suffix * - * @return mixed + * @param string $actionSuffix */ - public function getReturnedValue() {} + public function setActionSuffix(string $actionSuffix) {} /** - * Enable/Disable model binding during dispatch - * - * - * $di->set('dispatcher', function() { - * $dispatcher = new Dispatcher(); + * Sets the events manager * - * $dispatcher->setModelBinding(true, 'cache'); - * return $dispatcher; - * }); - * + * @param \Phalcon\Events\ManagerInterface $eventsManager + */ + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + + /** + * Sets the default suffix for the handler * - * @deprecated 3.1.0 Use setModelBinder method - * @see Phalcon\Dispatcher::setModelBinder() - * @param bool $value - * @param mixed $cache - * @deprecated - * @return Dispatcher + * @param string $handlerSuffix */ - public function setModelBinding($value, $cache = null) {} + public function setHandlerSuffix(string $handlerSuffix) {} /** * Enable model binding during dispatch * - * - * $di->set('dispatcher', function() { - * $dispatcher = new Dispatcher(); + * ```php + * $di->set( + * 'dispatcher', + * function() { + * $dispatcher = new Dispatcher(); * - * $dispatcher->setModelBinder(new Binder(), 'cache'); - * return $dispatcher; - * }); - * + * $dispatcher->setModelBinder( + * new Binder(), + * 'cache' + * ); + * + * return $dispatcher; + * } + * ); + * ``` * * @param \Phalcon\Mvc\Model\BinderInterface $modelBinder * @param mixed $cache * @return Dispatcher */ - public function setModelBinder(\Phalcon\Mvc\Model\BinderInterface $modelBinder, $cache = null) {} + public function setModelBinder(\Phalcon\Mvc\Model\BinderInterface $modelBinder, $cache = null): Dispatcher {} /** - * Gets model binder + * Sets the module where the controller is (only informative) * - * @return null|\Phalcon\Mvc\Model\BinderInterface + * @param string $moduleName */ - public function getModelBinder() {} + public function setModuleName(string $moduleName) {} /** - * Process the results of the router by calling into the appropriate controller action(s) - * including any routing data or injected parameters. - * - * @return object|false Returns the dispatched handler class (the Controller for Mvc dispatching or a Task - * for CLI dispatching) or false if an exception occurred and the operation was - * stopped by returning false in the exception handler. + * Sets the namespace where the controller class is * - * @throws \Exception if any uncaught or unhandled exception occurs during the dispatcher process. + * @param string $namespaceName */ - public function dispatch() {} + public function setNamespaceName(string $namespaceName) {} /** - * Forwards the execution flow to another controller/action. - * - * - * $this->dispatcher->forward( - * [ - * "controller" => "posts", - * "action" => "index", - * ] - * ); - * - * - * @param array forward + * Returns value returned by the latest dispatched action * - * @throws \Phalcon\Exception - * @param mixed $forward + * @return mixed */ - public function forward($forward) {} + public function getReturnedValue() {} /** * Check if the current executed action was forwarded by another one * * @return bool */ - public function wasForwarded() {} - - /** - * Possible class name that will be located to dispatch the request - * - * @return string - */ - public function getHandlerClass() {} - - /** - * @param mixed $handler - * @param string $actionMethod - * @param array $params - */ - public function callActionMethod($handler, $actionMethod, array $params = array()) {} + public function wasForwarded(): bool {} /** - * Returns bound models from binder instance - * - * - * class UserController extends Controller - * { - * public function showAction(User $user) - * { - * $boundModels = $this->dispatcher->getBoundModels(); // return array with $user - * } - * } - * - * - * @return array + * Set empty properties to their defaults (where defaults are available) */ - public function getBoundModels() {} + protected function resolveEmptyProperties() {} /** - * Set empty properties to their defaults (where defaults are available) + * @param string $input + * @return string */ - protected function _resolveEmptyProperties() {} + protected function toCamelCase(string $input): string {} } diff --git a/src/Phalcon/DispatcherInterface.php b/src/Phalcon/dispatcher/DispatcherInterface.php similarity index 63% rename from src/Phalcon/DispatcherInterface.php rename to src/Phalcon/dispatcher/DispatcherInterface.php index c7858384..e28b1de8 100644 --- a/src/Phalcon/DispatcherInterface.php +++ b/src/Phalcon/dispatcher/DispatcherInterface.php @@ -1,136 +1,149 @@ isCancelable()) { + * $event->stop(); + * } + * ``` + * + * @return bool */ - public function setData($data = null) {} + public function isCancelable(): bool {} /** - * Sets event type. + * Check whether the event is currently stopped. * - * @param string $type - * @return EventInterface + * @return bool */ - public function setType($type) {} + public function isStopped(): bool {} /** - * Stops the event preventing propagation. - * - * - * if ($event->isCancelable()) { - * $event->stop(); - * } - * + * Sets event data. * + * @param mixed $data * @return EventInterface */ - public function stop() {} + public function setData($data = null): EventInterface {} /** - * Check whether the event is currently stopped. + * Sets event type. * - * @return bool + * @param string $type + * @return EventInterface */ - public function isStopped() {} + public function setType(string $type): EventInterface {} /** - * Check whether the event is cancelable. + * Stops the event preventing propagation. * - * + * ```php * if ($event->isCancelable()) { * $event->stop(); * } - * + * ``` * - * @return bool + * @return EventInterface */ - public function isCancelable() {} + public function stop(): EventInterface {} } diff --git a/src/Phalcon/events/EventInterface.php b/src/Phalcon/events/EventInterface.php index de3427cc..92f60516 100644 --- a/src/Phalcon/events/EventInterface.php +++ b/src/Phalcon/events/EventInterface.php @@ -18,47 +18,47 @@ interface EventInterface public function getData(); /** - * Sets event data + * Gets event type * - * @param mixed $data - * @return EventInterface + * @return mixed */ - public function setData($data = null); + public function getType(); /** - * Gets event type + * Check whether the event is cancelable * - * @return mixed + * @return bool */ - public function getType(); + public function isCancelable(): bool; /** - * Sets event type + * Check whether the event is currently stopped * - * @param string $type - * @return EventInterface + * @return bool */ - public function setType($type); + public function isStopped(): bool; /** - * Stops the event preventing propagation + * Sets event data * + * @param mixed $data * @return EventInterface */ - public function stop(); + public function setData($data = null): EventInterface; /** - * Check whether the event is currently stopped + * Sets event type * - * @return bool + * @param string $type + * @return EventInterface */ - public function isStopped(); + public function setType(string $type): EventInterface; /** - * Check whether the event is cancelable + * Stops the event preventing propagation * - * @return bool + * @return EventInterface */ - public function isCancelable(); + public function stop(): EventInterface; } diff --git a/src/Phalcon/events/EventsAwareInterface.php b/src/Phalcon/events/EventsAwareInterface.php index 903a9bb8..a7fcff43 100644 --- a/src/Phalcon/events/EventsAwareInterface.php +++ b/src/Phalcon/events/EventsAwareInterface.php @@ -5,23 +5,24 @@ /** * Phalcon\Events\EventsAwareInterface * - * This interface must for those classes that accept an EventsManager and dispatch events + * This interface must for those classes that accept an EventsManager and + * dispatch events */ interface EventsAwareInterface { /** - * Sets the events manager + * Returns the internal event manager * - * @param ManagerInterface $eventsManager + * @return ManagerInterface */ - public function setEventsManager(ManagerInterface $eventsManager); + public function getEventsManager(): ManagerInterface; /** - * Returns the internal event manager + * Sets the events manager * - * @return ManagerInterface + * @param ManagerInterface $eventsManager */ - public function getEventsManager(); + public function setEventsManager(ManagerInterface $eventsManager); } diff --git a/src/Phalcon/events/Manager.php b/src/Phalcon/events/Manager.php index d1227745..39b3fb35 100644 --- a/src/Phalcon/events/Manager.php +++ b/src/Phalcon/events/Manager.php @@ -5,23 +5,31 @@ /** * Phalcon\Events\Manager * - * Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, - * the normal flow of operation. With the EventsManager the developer can create hooks or - * plugins that will offer monitoring of data, manipulation, conditional execution and much more. + * Phalcon Events Manager, offers an easy way to intercept and manipulate, if + * needed, the normal flow of operation. With the EventsManager the developer + * can create hooks or plugins that will offer monitoring of data, manipulation, + * conditional execution and much more. */ class Manager implements \Phalcon\Events\ManagerInterface { - protected $_events = null; + const DEFAULT_PRIORITY = 100; + /** + * @var bool + */ + protected $collect = false; - protected $_collect = false; + /** + * @var bool + */ + protected $enablePriorities = false; - protected $_enablePriorities = false; + protected $events = null; - protected $_responses; + protected $responses; /** @@ -31,83 +39,85 @@ class Manager implements \Phalcon\Events\ManagerInterface * @param object|callable $handler * @param int $priority */ - public function attach($eventType, $handler, $priority = 100) {} + public function attach(string $eventType, $handler, int $priority = self::DEFAULT_PRIORITY) {} /** - * Detach the listener from the events manager + * Returns if priorities are enabled * - * @param string $eventType - * @param object $handler + * @return bool */ - public function detach($eventType, $handler) {} + public function arePrioritiesEnabled(): bool {} /** - * Set if priorities are enabled in the EventsManager + * Tells the event manager if it needs to collect all the responses returned + * by every registered listener in a single fire * - * @param bool $enablePriorities + * @param bool $collect */ - public function enablePriorities($enablePriorities) {} + public function collectResponses(bool $collect) {} /** - * Returns if priorities are enabled + * Detach the listener from the events manager * - * @return bool + * @param string $eventType + * @param object $handler */ - public function arePrioritiesEnabled() {} + public function detach(string $eventType, $handler) {} /** - * Tells the event manager if it needs to collect all the responses returned by every - * registered listener in a single fire + * Removes all events from the EventsManager * - * @param bool $collect + * @param string $type */ - public function collectResponses($collect) {} + public function detachAll(string $type = null) {} /** - * Check if the events manager is collecting all all the responses returned by every - * registered listener in a single fire + * Set if priorities are enabled in the EventsManager * - * @return bool + * @param bool $enablePriorities */ - public function isCollecting() {} + public function enablePriorities(bool $enablePriorities) {} /** - * Returns all the responses returned by every handler executed by the last 'fire' executed + * Fires an event in the events manager causing the active listeners to be + * notified about it * - * @return array - */ - public function getResponses() {} - - /** - * Removes all events from the EventsManager + * ```php + * $eventsManager->fire("db", $connection); + * ``` * - * @param string $type + * @param string $eventType + * @param object $source + * @param mixed $data + * @param bool $cancelable + * @return mixed */ - public function detachAll($type = null) {} + public function fire(string $eventType, $source, $data = null, bool $cancelable = true) {} /** * Internal handler to call a queue of events * - * @param \SplPriorityQueue|array $queue - * @param \Phalcon\Events\Event $event + * @param \SplPriorityQueue $queue + * @param EventInterface $event * @return mixed */ - public final function fireQueue($queue, EventInterface $event) {} + final public function fireQueue(\SplPriorityQueue $queue, EventInterface $event) {} /** - * Fires an event in the events manager causing the active listeners to be notified about it + * Returns all the attached listeners of a certain type * - * - * $eventsManager->fire("db", $connection); - * + * @param string $type + * @return array + */ + public function getListeners(string $type): array {} + + /** + * Returns all the responses returned by every handler executed by the last + * 'fire' executed * - * @param string $eventType - * @param object $source - * @param mixed $data - * @param boolean $cancelable - * @return mixed + * @return array */ - public function fire($eventType, $source, $data = null, $cancelable = true) {} + public function getResponses(): array {} /** * Check whether certain type of event has listeners @@ -115,14 +125,14 @@ public function fire($eventType, $source, $data = null, $cancelable = true) {} * @param string $type * @return bool */ - public function hasListeners($type) {} + public function hasListeners(string $type): bool {} /** - * Returns all the attached listeners of a certain type + * Check if the events manager is collecting all all the responses returned + * by every registered listener in a single fire * - * @param string $type - * @return array + * @return bool */ - public function getListeners($type) {} + public function isCollecting(): bool {} } diff --git a/src/Phalcon/events/ManagerInterface.php b/src/Phalcon/events/ManagerInterface.php index 0598a8c4..048672ab 100644 --- a/src/Phalcon/events/ManagerInterface.php +++ b/src/Phalcon/events/ManagerInterface.php @@ -5,9 +5,10 @@ /** * Phalcon\Events\Manager * - * Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, - * the normal flow of operation. With the EventsManager the developer can create hooks or - * plugins that will offer monitoring of data, manipulation, conditional execution and much more. + * Phalcon Events Manager, offers an easy way to intercept and manipulate, if + * needed, the normal flow of operation. With the EventsManager the developer + * can create hooks or plugins that will offer monitoring of data, manipulation, + * conditional execution and much more. */ interface ManagerInterface { @@ -18,7 +19,7 @@ interface ManagerInterface * @param string $eventType * @param object|callable $handler */ - public function attach($eventType, $handler); + public function attach(string $eventType, $handler); /** * Detach the listener from the events manager @@ -26,24 +27,25 @@ public function attach($eventType, $handler); * @param string $eventType * @param object $handler */ - public function detach($eventType, $handler); + public function detach(string $eventType, $handler); /** * Removes all events from the EventsManager * * @param string $type */ - public function detachAll($type = null); + public function detachAll(string $type = null); /** - * Fires an event in the events manager causing the active listeners to be notified about it + * Fires an event in the events manager causing the active listeners to be + * notified about it * * @param string $eventType * @param object $source * @param mixed $data * @return mixed */ - public function fire($eventType, $source, $data = null); + public function fire(string $eventType, $source, $data = null); /** * Returns all the attached listeners of a certain type @@ -51,6 +53,14 @@ public function fire($eventType, $source, $data = null); * @param string $type * @return array */ - public function getListeners($type); + public function getListeners(string $type): array; + + /** + * Check whether certain type of event has listeners + * + * @param string $type + * @return bool + */ + public function hasListeners(string $type): bool; } diff --git a/src/Phalcon/factory/AbstractFactory.php b/src/Phalcon/factory/AbstractFactory.php new file mode 100644 index 00000000..b54cb01b --- /dev/null +++ b/src/Phalcon/factory/AbstractFactory.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class AbstractFactory +{ + /** + * @var array + */ + protected $mapper = array(); + + /** + * @var array + */ + protected $services = array(); + + + /** + * Checks if a service exists and throws an exception + * + * @param string $name + */ + protected function checkService(string $name) {} + + /** + * Checks the config if it is a valid object + * + * @param mixed $config + * @return array + */ + protected function checkConfig($config): array {} + + /** + * Returns the adapters for the factory + * + * @return array + */ + abstract protected function getAdapters(): array; + + /** + * AdapterFactory constructor. + * + * @param array $services + */ + protected function init(array $services = array()) {} + +} diff --git a/src/Phalcon/factory/Exception.php b/src/Phalcon/factory/Exception.php index 25a41d41..15f9cdc3 100644 --- a/src/Phalcon/factory/Exception.php +++ b/src/Phalcon/factory/Exception.php @@ -3,9 +3,12 @@ namespace Phalcon\Factory; /** - * Phalcon\Factory\Exception + * This file is part of the Phalcon Framework. * - * Exceptions thrown in Phalcon\Factory will use this class + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. */ class Exception extends \Phalcon\Exception { diff --git a/src/Phalcon/filter/Filter.php b/src/Phalcon/filter/Filter.php new file mode 100644 index 00000000..ad2a7516 --- /dev/null +++ b/src/Phalcon/filter/Filter.php @@ -0,0 +1,154 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class FilterFactory +{ + + /** + * Returns a Locator object with all the helpers defined in anonynous + * functions + * + * @return LocatorInterface + */ + public function newInstance(): LocatorInterface {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/filter/FilterInterface.php b/src/Phalcon/filter/FilterInterface.php new file mode 100644 index 00000000..067ba31c --- /dev/null +++ b/src/Phalcon/filter/FilterInterface.php @@ -0,0 +1,21 @@ + + */ + protected $cache; + + /** + * Default access + * + * @var int + */ + protected $defaultAccess = Enum::DENY; + + /** + * Events manager + * + * @var mixed + */ + protected $eventsManager; + + /** + * Internal cache for caching access during request time + * + * @var mixed + */ + protected $internalCache; + + /** + * Anonymous function for getting user identity - this function must + * return string, array or object implementing Phalcon\Acl\RoleAware + * + * @var mixed + */ + protected $roleCallback; + + + /** + * Storing active identity object implementing Phalcon/Acl/RoleAware + */ + public function getActiveIdentity() {} + + /** + * Storing active user role + */ + public function getActiveRole() {} + + /** + * Should role always be resolved using role callback or just once? + * + * @param bool $alwaysResolvingRole + */ + public function setAlwaysResolvingRole(bool $alwaysResolvingRole) {} + + /** + * Default access + * + * @return int + */ + public function getDefaultAccess(): int {} + + /** + * Returns the internal event manager + * + * @return \Phalcon\Events\ManagerInterface + */ + public function getEventsManager(): ManagerInterface {} + + /** + * Gets role callback to fetch role name + * + * @return \Closure + */ + public function getRoleCallback(): Closure {} + + /** + * Gets always resolving role option + * + * @return bool + */ + public function isAlwaysResolvingRole(): bool {} + + /** + * Sets the cache adapter + * + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache + * @return AdapterInterface + */ + public function setCache(\Phalcon\Cache\Adapter\AdapterInterface $cache): AdapterInterface {} + + /** + * Sets the default access level (Phalcon\Acl\Enum::ALLOW or Phalcon\Acl\Enum::DENY) + * + * @param int $defaultAccess + * @return AdapterInterface + */ + public function setDefaultAccess(int $defaultAccess): AdapterInterface {} + + /** + * Sets the events manager + * + * @param \Phalcon\Events\ManagerInterface $eventsManager + * @return AdapterInterface + */ + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager): AdapterInterface {} + + /** + * Sets role callback to fetch role name + * + * @param mixed $callback + * @return AdapterInterface + */ + public function setRoleCallback($callback): AdapterInterface {} + + /** + * @param \Phalcon\Di\DiInterface $container + */ + protected function callRoleCallback(\Phalcon\Di\DiInterface $container) {} + + /** + * Gets access from cache + * + * @param string $key + * @param array $originalValues + * @param string $roleCacheKey + * @return bool|null + */ + protected function getAccessFromCache(string $key, array $originalValues = null, string $roleCacheKey = null): ?bool {} + + /** + * Handles a user exception + * + * @param \Exception $exception + */ + protected function handleException(\Exception $exception) {} + + /** + * Fires event or throwing exception + * + * @param mixed $role + * @param string $actionName + * @param string $controllerName + * @param bool $access + */ + protected function fireEventOrThrowException($role, string $actionName, string $controllerName, bool $access) {} + + /** + * Saves access in cache and internal cache + * + * @param string $key + * @param bool $access + */ + protected function saveAccessInCache(string $key, bool $access) {} + + /** + * Throws an internal exception + * + * @param string $message + * @param int $exceptionCode + * @return bool + */ + protected function throwFirewallException(string $message, int $exceptionCode = 0): bool {} + +} diff --git a/src/Phalcon/firewall/adapter/Acl.php b/src/Phalcon/firewall/adapter/Acl.php new file mode 100644 index 00000000..7ac99290 --- /dev/null +++ b/src/Phalcon/firewall/adapter/Acl.php @@ -0,0 +1,174 @@ +success("The record was successfully deleted"); + * $flash->error("Cannot open the file"); + * ``` + */ +abstract class AbstractFlash implements \Phalcon\Flash\FlashInterface, \Phalcon\Di\InjectionAwareInterface +{ + /** + * @var bool + */ + protected $autoescape = true; + + /** + * @var bool + */ + protected $automaticHtml = true; + + /** + * @var array + */ + protected $cssClasses = array(); + + /** + * @var string + */ + protected $customTemplate = ''; + + + protected $container = null; + + + protected $escaperService = null; + + /** + * @var bool + */ + protected $implicitFlush = true; + + + protected $messages = array(); + + + /** + * Phalcon\Flash constructor + * + * @param mixed $cssClasses + */ + public function __construct($cssClasses = null) {} + + /** + * Clears accumulated messages when implicit flush is disabled + */ + public function clear() {} + + /** + * Shows a HTML error message + * + * ```php + * $flash->error("This is an error"); + * ``` + * + * @param string $message + * @return string + */ + public function error(string $message): string {} + + /** + * Returns the autoescape mode in generated html + * + * @return bool + */ + public function getAutoescape(): bool {} + + /** + * Returns the custom template set + * + * @return string + */ + public function getCustomTemplate(): string {} + + /** + * Returns the internal dependency injector + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Returns the Escaper Service + * + * @return \Phalcon\Escaper\EscaperInterface + */ + public function getEscaperService(): EscaperInterface {} + + /** + * Shows a HTML notice/information message + * + * ```php + * $flash->notice("This is an information"); + * ``` + * + * @param string $message + * @return string + */ + public function notice(string $message): string {} + + /** + * Set the autoescape mode in generated html + * + * @param bool $autoescape + * @return Flash + */ + public function setAutoescape(bool $autoescape): Flash {} + + /** + * Set if the output must be implicitly formatted with HTML + * + * @param bool $automaticHtml + * @return FlashInterface + */ + public function setAutomaticHtml(bool $automaticHtml): FlashInterface {} + + /** + * Set an array with CSS classes to format the messages + * + * @param array $cssClasses + * @return FlashInterface + */ + public function setCssClasses(array $cssClasses): FlashInterface {} + + /** + * Set an custom template for showing the messages + * + * @param string $customTemplate + * @return FlashInterface + */ + public function setCustomTemplate(string $customTemplate): FlashInterface {} + + /** + * Sets the dependency injector + * + * @param \Phalcon\Di\DiInterface $container + * @return FlashInterface + */ + public function setDI(\Phalcon\Di\DiInterface $container): FlashInterface {} + + /** + * Sets the Escaper Service + * + * @param \Phalcon\Escaper\EscaperInterface $escaperService + * @return FlashInterface + */ + public function setEscaperService(\Phalcon\Escaper\EscaperInterface $escaperService): FlashInterface {} + + /** + * Set whether the output must be implicitly flushed to the output or + * returned as string + * + * @param bool $implicitFlush + * @return FlashInterface + */ + public function setImplicitFlush(bool $implicitFlush): FlashInterface {} + + /** + * Shows a HTML success message + * + * ```php + * $flash->success("The process was finished successfully"); + * ``` + * + * @param string $message + * @return string + */ + public function success(string $message): string {} + + /** + * Outputs a message formatting it with HTML + * + * ```php + * $flash->outputMessage("error", $message); + * ``` + * + * @param string $type + * @param string|array $message + * @return string|void + */ + public function outputMessage(string $type, $message) {} + + /** + * Shows a HTML warning message + * + * ```php + * $flash->warning("Hey, this is important"); + * ``` + * + * @param string $message + * @return string + */ + public function warning(string $message): string {} + + /** + * @param string $cssClassses + * @return string + */ + private function getTemplate(string $cssClassses): string {} + + /** + * Returns the message escaped if the autoEscape is true, otherwise the + * original message is returned + * + * @param string $message + * @return string + */ + private function prepareEscapedMessage(string $message): string {} + + /** + * Prepares the HTML output for the message. If automaticHtml is not set + * then the original message is returned + * + * @param string $type + * @param string $message + * @return string + */ + private function prepareHtmlMessage(string $type, string $message): string {} + +} diff --git a/src/Phalcon/flash/Direct.php b/src/Phalcon/flash/Direct.php index bfe09e23..fda928b6 100644 --- a/src/Phalcon/flash/Direct.php +++ b/src/Phalcon/flash/Direct.php @@ -3,11 +3,10 @@ namespace Phalcon\Flash; /** - * Phalcon\Flash\Direct - * - * This is a variant of the Phalcon\Flash that immediately outputs any message passed to it + * This is a variant of the Phalcon\Flash that immediately outputs any message + * passed to it */ -class Direct extends \Phalcon\Flash +class Direct extends \Phalcon\Flash\AbstractFlash { /** @@ -17,13 +16,13 @@ class Direct extends \Phalcon\Flash * @param mixed $message * @return string */ - public function message($type, $message) {} + public function message(string $type, $message): string {} /** * Prints the messages accumulated in the flasher * * @param bool $remove */ - public function output($remove = true) {} + public function output(bool $remove = true) {} } diff --git a/src/Phalcon/flash/Exception.php b/src/Phalcon/flash/Exception.php index fece45ed..6a123e85 100644 --- a/src/Phalcon/flash/Exception.php +++ b/src/Phalcon/flash/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Flash; /** - * Phalcon\Flash\Exception - * * Exceptions thrown in Phalcon\Flash will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/flash/FlashInterface.php b/src/Phalcon/flash/FlashInterface.php new file mode 100644 index 00000000..8faa3dea --- /dev/null +++ b/src/Phalcon/flash/FlashInterface.php @@ -0,0 +1,53 @@ + + * ```php * if ($form->isValid($_POST) == false) { - * // Get messages separated by the item name - * // $messages is an array of Group object - * $messages = $form->getMessages(true); - * - * foreach ($messages as $message) { - * echo $message, "
"; - * } - * - * // Default behavior. - * // $messages is a Group object * $messages = $form->getMessages(); * * foreach ($messages as $message) { * echo $message, "
"; * } * } - * + * ``` * - * @param bool $byItemName - * @return array|\Phalcon\Validation\Message\Group + * @return array|\Phalcon\Messages\Messages */ - public function getMessages($byItemName = false) {} + public function getMessages() {} /** * Returns the messages generated for a specific element * * @param string $name - * @return \Phalcon\Validation\Message\Group + * @return \Phalcon\Messages\Messages */ - public function getMessagesFor($name) {} + public function getMessagesFor(string $name): Messages {} /** - * Check if messages were generated for a specific element + * Returns the value of an option if present * - * @param string $name - * @return bool + * @param string $option + * @param mixed $defaultValue + * @return mixed */ - public function hasMessagesFor($name) {} + public function getUserOption(string $option, $defaultValue = null) {} /** - * Adds an element to the form + * Returns the options for the element * - * @param \Phalcon\Forms\ElementInterface $element - * @param string $position - * @param bool $type - * @return Form + * @return array */ - public function add(\Phalcon\Forms\ElementInterface $element, $position = null, $type = null) {} + public function getUserOptions(): array {} /** - * Renders a specific item in the form + * Gets a value from the internal related entity or from the default value * * @param string $name - * @param array $attributes - * @return string + * @return mixed|null */ - public function render($name, $attributes = null) {} + public function getValue(string $name): ? {} /** - * Returns an element added to the form by its name + * Check if the form contains an element * * @param string $name - * @return \Phalcon\Forms\ElementInterface + * @return bool */ - public function get($name) {} + public function has(string $name): bool {} /** - * Generate the label of an element added to the form including HTML + * Check if messages were generated for a specific element * * @param string $name - * @param array $attributes - * @return string + * @return bool */ - public function label($name, array $attributes = null) {} + public function hasMessagesFor(string $name): bool {} /** - * Returns a label for an element + * Validates the form * - * @param string $name - * @return string + * @param array $data + * @param object $entity + * @return bool */ - public function getLabel($name) {} + public function isValid($data = null, $entity = null): bool {} /** - * Gets a value from the internal related entity or from the default value + * Returns the current position/key in the iterator + * + * @return int + */ + public function key(): int {} + + /** + * Generate the label of an element added to the form including HTML * * @param string $name - * @return mixed|null + * @param array $attributes + * @return string */ - public function getValue($name) {} + public function label(string $name, array $attributes = null): string {} /** - * Check if the form contains an element + * Moves the internal iteration pointer to the next position + */ + public function next() {} + + /** + * Renders a specific item in the form * * @param string $name - * @return bool + * @param array $attributes + * @return string */ - public function has($name) {} + public function render(string $name, array $attributes = array()): string {} /** * Removes an element from the form @@ -252,52 +240,66 @@ public function has($name) {} * @param string $name * @return bool */ - public function remove($name) {} + public function remove(string $name): bool {} /** - * Clears every element in the form to its default value + * Rewinds the internal iterator + */ + public function rewind() {} + + /** + * Sets the form's action * - * @param array $fields + * @param string $action * @return Form */ - public function clear($fields = null) {} + public function setAction(string $action): Form {} /** - * Returns the number of elements in the form + * Sets the entity related to the model * - * @return int + * @param object $entity + * @return Form */ - public function count() {} + public function setEntity($entity): Form {} /** - * Rewinds the internal iterator + * Sets an option for the form + * + * @param string $option + * @param mixed $value + * @return Form */ - public function rewind() {} + public function setUserOption(string $option, $value): Form {} /** - * Returns the current element in the iterator + * Sets options for the element * - * @return bool|\Phalcon\Forms\ElementInterface + * @param array $options + * @return Form */ - public function current() {} + public function setUserOptions(array $options): Form {} /** - * Returns the current position/key in the iterator + * Check if the current element in the iterator is valid * - * @return int + * @return bool */ - public function key() {} + public function valid(): bool {} /** - * Moves the internal iteration pointer to the next position + * Get Form attributes collection + * + * @return \Phalcon\Html\Attributes */ - public function next() {} + public function getAttributes(): Attributes {} /** - * Check if the current element in the iterator is valid + * Set form attributes collection * - * @return bool + * @param \Phalcon\Html\Attributes $attributes + * @return \Phalcon\Html\Attributes\AttributesInterface */ - public function valid() {} + public function setAttributes(\Phalcon\Html\Attributes $attributes): AttributesInterface {} } diff --git a/src/Phalcon/forms/Manager.php b/src/Phalcon/forms/Manager.php index 7a74031c..df4e51a2 100644 --- a/src/Phalcon/forms/Manager.php +++ b/src/Phalcon/forms/Manager.php @@ -3,12 +3,12 @@ namespace Phalcon\Forms; /** - * Phalcon\Forms\Manager + * Forms Manager */ class Manager { - protected $_forms; + protected $forms = array(); /** @@ -18,7 +18,7 @@ class Manager * @param object $entity * @return Form */ - public function create($name, $entity = null) {} + public function create(string $name, $entity = null): Form {} /** * Returns a form by its name @@ -26,7 +26,7 @@ public function create($name, $entity = null) {} * @param string $name * @return Form */ - public function get($name) {} + public function get(string $name): Form {} /** * Checks if a form is registered in the forms manager @@ -34,7 +34,7 @@ public function get($name) {} * @param string $name * @return bool */ - public function has($name) {} + public function has(string $name): bool {} /** * Registers a form in the Forms Manager @@ -43,6 +43,6 @@ public function has($name) {} * @param Form $form * @return FormManager */ - public function set($name, Form $form) {} + public function set(string $name, Form $form): FormManager {} } diff --git a/src/Phalcon/forms/Element.php b/src/Phalcon/forms/element/AbstractElement.php similarity index 58% rename from src/Phalcon/forms/Element.php rename to src/Phalcon/forms/element/AbstractElement.php index 6c832bf0..5a9385cd 100644 --- a/src/Phalcon/forms/Element.php +++ b/src/Phalcon/forms/element/AbstractElement.php @@ -1,226 +1,227 @@ %label%"; + private $template = '
%label%
'; + + + /** + * Crumb separator + * + * @return string + */ + public function getSeparator(): string {} + + /** + * Crumb separator + * + * @param string $separator + */ + public function setSeparator(string $separator) {} /** * Adds a new crumb. * - * + * ```php * // Adding a crumb with a link * $breadcrumbs->add("Home", "/"); * * // Adding a crumb without a link (normally the last one) * $breadcrumbs->add("Users"); - * + * ``` + * + * @param string $label + * @param string $link + * @return Breadcrumbs */ - public function add(string $label, string $link = "") : Breadcrumbs - { - } + public function add(string $label, string $link = ''): Breadcrumbs {} /** - * Clears the crumbx + * Clears the crumbs * - * + * ```php * $breadcrumbs->clear() - * + * ``` */ - public function clear() : void - { - } + public function clear() {} /** * Removes crumb by url. * - * + * ```php * $breadcrumbs->remove("/admin/user/create"); * * // remove a crumb without an url (last link) * $breadcrumbs->remove(); - * + * ``` + * + * @param string $link */ - public function remove(string $link) : void - { - } + public function remove(string $link) {} /** * Renders and outputs breadcrumbs based on previously set template. * - * - * // Php Engine + * ```php * echo $breadcrumbs->render(); - * + * ``` + * + * @return string */ - public function render() : string - { - } + public function render(): string {} /** * Returns the internal breadcrumbs array + * + * @return array */ - public function toArray() : array - { - } + public function toArray(): array {} + } diff --git a/src/Phalcon/html/Exception.php b/src/Phalcon/html/Exception.php index 1a22c6d9..2a33e680 100644 --- a/src/Phalcon/html/Exception.php +++ b/src/Phalcon/html/Exception.php @@ -6,7 +6,6 @@ * Phalcon\Html\Tag\Exception * * Exceptions thrown in Phalcon\Html\Tag will use this class - * */ class Exception extends \Phalcon\Exception { diff --git a/src/Phalcon/html/Tag.php b/src/Phalcon/html/Tag.php index 864cb02b..ee523d93 100644 --- a/src/Phalcon/html/Tag.php +++ b/src/Phalcon/html/Tag.php @@ -2,1063 +2,1181 @@ namespace Phalcon\Html; -use Phalcon\DiInterface; -use Phalcon\Di\InjectionAwareInterface; -use Phalcon\Escaper; -use Phalcon\EscaperInterface; -use Phalcon\Helper\Arr; -use Phalcon\Html\Exception; -use Phalcon\UrlInterface; - /** * Phalcon\Html\Tag * - * Phalcon\Tag is designed to simplify building of HTML tags. It provides a set - * of helpers to dynamically generate HTML. + * Phalcon\Html\Tag is designed to simplify building of HTML tags. It provides a + * set of helpers to dynamically generate HTML. */ -class Tag implements InjectionAwareInterface +class Tag implements \Phalcon\Di\InjectionAwareInterface { - /** - * @var - */ - protected $container; - - /** - * @var array - */ - private $append = []; - - /** - * @var int - */ - private $docType = 5; // HTML5 - - /** - * @var - */ - private $escaper; - - /** - * @var array - */ - private $prepend = []; - - /** - * @var string - */ - private $separator = ""; - - /** - * @var string - */ - private $title = ""; - - /** - * @var array - */ - private $values = []; - - /** - * @var - */ - private $url; - - /** - * Constants - */ - const HTML32 = 1; - const HTML401_STRICT = 2; - const HTML401_TRANSITIONAL = 3; - const HTML401_FRAMESET = 4; - const HTML5 = 5; - const XHTML10_STRICT = 6; - const XHTML10_TRANSITIONAL = 7; - const XHTML10_FRAMESET = 8; - const XHTML11 = 9; - const XHTML20 = 10; - const XHTML5 = 11; - - /** - * Appends a text to current document title - */ - public function appendTitle(array $title) : Tag - { - } - - /** - * Builds a HTML input[type="button"] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->button('Click Me') - * - * - * Volt syntax: - * - * {{ button('Click Me) }} - * - */ - public function button(string $name, array $parameters = []) : string - { - } - - /** - * Resets the request and internal values to avoid those fields will have - * any default value. - */ - public function clear() : void - { - } - - /** - * Builds a HTML tag - * - * Parameters - * `onlyStart` Only process the start of th element - * `selfClose` It is a self close element - * `useEol` Append PHP_EOL at the end - * - */ - public function element(string $tag, array $parameters = []) : string - { - } - - /** - * Builds the closing tag of an html element - * - * Parameters - * `useEol` Append PHP_EOL at the end - * - * - * use Phalcon\Html\Tag; - * - * $tab = new Tag(); - * - * echo $tag->elementClose( - * [ - * 'name' => 'aside', + /** + * Constants + */ + const HTML32 = 1; + + + const HTML401_STRICT = 2; + + + const HTML401_TRANSITIONAL = 3; + + + const HTML401_FRAMESET = 4; + + + const HTML5 = 5; + + + const XHTML10_STRICT = 6; + + + const XHTML10_TRANSITIONAL = 7; + + + const XHTML10_FRAMESET = 8; + + + const XHTML11 = 9; + + + const XHTML20 = 10; + + + const XHTML5 = 11; + + /** + * @var DiInterface + */ + protected $container; + + /** + * @var array + */ + private $append = array(); + + /** + * @var int + */ + private $docType = 5; + + /** + * @var + */ + private $escaper; + + /** + * @var array + */ + private $prepend = array(); + + /** + * @var string + */ + private $separator = ''; + + /** + * @var string + */ + private $title = ''; + + /** + * @var array + */ + private $values = array(); + + /** + * @var + */ + private $url; + + + /** + * Constructor + * + * @param \Phalcon\Escaper\EscaperInterface $escaper + * @param \Phalcon\Url\UrlInterface $url + */ + public function __construct(\Phalcon\Escaper\EscaperInterface $escaper = null, \Phalcon\Url\UrlInterface $url = null) {} + + /** + * Appends a text to current document title + * + * @param mixed $title + * @return Tag + */ + public function appendTitle($title): Tag {} + + /** + * Builds a HTML input[type="button"] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->button('Click Me'); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ button('Click Me') }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function button(string $name, array $parameters = array()): string {} + + /** + * Resets the request and internal values to avoid those fields will have + * any default value. + */ + public function clear() {} + + /** + * Builds a HTML tag + * + * Parameters + * `onlyStart` Only process the start of th element + * `selfClose` It is a self close element + * `useEol` Append PHP_EOL at the end + * + * @param string $tag + * @param array $parameters + * @return string + */ + public function element(string $tag, array $parameters = array()): string {} + + /** + * Builds the closing tag of an html element + * + * Parameters + * `useEol` Append PHP_EOL at the end + * + * ```php + * use Phalcon\Html\Tag; + * + * $tab = new Tag(); + * + * echo $tag->elementClose( + * [ + * 'name' => 'aside', * ] * ); // - * - * echo $tag->elementClose( - * [ - * 'name' => 'aside', - * 'useEol' => true, - * ] - * ); // '' . PHP_EOL - * - * - */ - public function elementClose(string $tag, array $parameters = []) : string - { - } - - /** - * Returns the closing tag of a form element - */ - public function endForm(bool $eol = true) : string - { - } - - /** - * Builds a HTML FORM tag - * - * - * use Phalcon\Html\Tag; - * - * $tab = new Tag(); - * - * echo $tag->form('posts/save'); - * - * echo $tag->form( - * 'posts/save', - * [ - * "method" => "post", - * ] - * ); - * - * - * Volt syntax: - * - * {{ form('posts/save') }} - * {{ form('posts/save', ['method': 'post') }} - * - */ - public function form(string $action, array $parameters = []) : string - { - } - - /** - * Converts text to URL-friendly strings - * - * Parameters - * `text` The text to be processed - * `separator` Separator to use (default '-') - * `lowercase` Convert to lowercase - * `replace` - * - * - * use Phalcon\Html\Tag; - * - * $tab = new Tag(); - * - * echo $tag->friendlyTitle( - * [ - * 'text' => 'These are big important news', - * 'separator' => '-', - * ] - * ); - * - * - * Volt Syntax: - * - * {{ friendly_title(['text': 'These are big important news', 'separator': '-']) }} - * - */ - public function friendlyTitle(string $text, array $parameters = []) : string - { - } - - /** - * Returns the internal dependency injector - */ - public function getDI() : DiInterface - { - } - - /** - * Get the document type declaration of content. If the docType has not - * been set properly, XHTML5 is returned - */ - public function getDocType() : string - { - } - - /** - * Gets the current document title. The title will be automatically escaped. - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * $tag - * ->setTitleSeparator(' ') - * ->prependTitle(['Hello']) - * ->setTitle('World') - * ->appendTitle(['from Phalcon']); - * - * echo $tag->getTitle(); // Hello World from Phalcon - * echo $tag->getTitle(false); // World from Phalcon - * echo $tag->getTitle(true, false); // Hello World - * echo $tag->getTitle(false, false); // World - * - * - * Volt syntax: - * - * {{ get_title() }} - * - */ - public function getTitle(bool $prepend = true, bool $append = true) : string - { - } - - /** - * Gets the current document title separator - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->getTitleSeparator(); - * - * - * Volt syntax: - * - * {{ get_title_separator() }} - * - */ - public function getTitleSeparator() : string - { - } - - /** - * Every helper calls this function to check whether a component has a predefined - * value using `setAttribute` or value from $_POST - */ - public function getValue(string $name, array $parameters = []) { - } - - /** - * Check if a helper has a default value set using `setAttribute()` or - * value from $_POST - */ - public function hasValue(string $name) : bool - { - } - - /** - * Builds HTML IMG tags - * - * Parameters - * `local` Local resource or not (default `true`) - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->image('img/bg.png'); - * - * echo $tag->image( - * 'img/photo.jpg', - * [ - * 'alt' => 'Some Photo', - * ] - * ); - * - * echo $tag->image( - * 'http://static.mywebsite.com/img/bg.png', - * [ - * 'local' => false, - * ] - * ); - * - * - * Volt Syntax: - * - * {{ image('img/bg.png') }} - * {{ image('img/photo.jpg', ['alt': 'Some Photo') }} - * {{ image('http://static.mywebsite.com/img/bg.png', ['local': false]) }} - * - */ - public function image(string $url = "", array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type="check"] tag - * - * - * echo $tag->inputCheckbox( - * [ - * 'name' => 'terms, - * 'value' => 'Y', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_checkbox(['name': 'terms, 'value': 'Y']) }} - * - * - * @param array parameters - */ - public function inputCheckbox(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='color'] tag - */ - public function inputColor(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='date'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputDate( - * [ - * 'name' => 'born', - * 'value' => '14-12-1980', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_date(['name':'born', 'value':'14-12-1980']) }} - * - */ - public function inputDate(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='datetime'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputDateTime( - * [ - * 'name' => 'born', - * 'value' => '14-12-1980', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_date_time(['name':'born', 'value':'14-12-1980']) }} - * - */ - public function inputDateTime(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='datetime-local'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputDateTimeLocal( - * [ - * 'name' => 'born', - * 'value' => '14-12-1980', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_date_time_local(['name':'born', 'value':'14-12-1980']) }} - * - */ - public function inputDateTimeLocal(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='email'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputEmail( - * [ - * 'name' => 'email', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_email(['name': 'email']); - * - */ - public function inputEmail(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='file'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputFile( - * [ - * 'name' => 'file', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_file(['name': 'file']); - * - */ - public function inputFile(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='hidden'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputHidden( - * [ - * 'name' => 'my-field', - * 'value' => 'mike', - * ] - * ); - * - */ - public function inputHidden(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type="image"] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * echo $tag->inputImage( - * [ - * 'src' => '/img/button.png', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_image(['src': '/img/button.png']) }} - * - */ - public function inputImage(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='month'] tag - */ - public function inputMonth(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='number'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->numericField( - * [ - * 'name' => 'price', - * 'min' => '1', - * 'max' => '5', - * ] - * ); - * - */ - public function inputNumeric(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='password'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->passwordField( - * [ - * 'name' => 'my-field', - * 'size' => 30, - * ] - * ); - * - */ - public function inputPassword(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type="radio"] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputRadio( - * [ - * 'name' => 'weather', - * 'value" => 'hot', - * ] - * ); - * - * - * Volt syntax: - * - * {{ input_radio(['name': 'weather', 'value": 'hot']) }} - * - */ - public function inputRadio(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='range'] tag - */ - public function inputRange(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='search'] tag - */ - public function inputSearch(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='tel'] tag - */ - public function inputTel(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='text'] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->inputText( - * [ - * 'name' => 'my-field', - * 'size' => 30, - * ] - * ); - * - */ - public function inputText(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='time'] tag - */ - public function inputTime(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='url'] tag - */ - public function inputUrl(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type='week'] tag - */ - public function inputWeek(string $name, array $parameters = []) : string - { - } - - /** - * Builds a script[type="javascript"] tag - * - * Parameters - * `local` Local resource or not (default `true`) - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * echo $tag->javascript( - * 'http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js', - * ['local' => false] - * ); - * echo $tag->javascript('javascript/jquery.js'); - * - * - * Volt syntax: - * - * {{ javascript('http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js', ['local': false]) }} - * {{ javascript('javascript/jquery.js') }} - * - */ - public function javascript(string $url, array $parameters = []) : string - { - } - - /** - * Builds a HTML A tag using framework conventions - * - * Parameters - * `local` Local resource or not (default `true`) - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->link('signup/register', 'Register Here!'); - * - * echo $tag->link( - * 'signup/register', - * 'Register Here!', - * [ - * 'class' => 'btn-primary', - * ] - * ); - * - * echo $tag->link( - * 'https://phalconphp.com/', - * 'Phalcon!', - * [ - * 'local' => false, - * ] - * ); - * - * echo $tag->linkTo( - * 'https://phalconphp.com/', - * 'Phalcon!', - * [ - * 'local' => false, - * 'target' => '_new' - * ] - * ); - * - * - */ - public function link(string $url, string $text = "", array $parameters = []) : string - { - } - - /** - * Prepends a text to current document title - */ - public function prependTitle(array $title) : Tag - { - } - - /** - * Renders the title with title tags. The title is automaticall escaped - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * $tag - * ->setTitleSeparator(' ') - * ->prependTitle(['Hello']) - * ->setTitle('World') - * ->appendTitle(['from Phalcon']); - * - * echo $tag->renderTitle(); // Hello World from Phalcon - * echo $tag->renderTitle(false); // World from Phalcon - * echo $tag->renderTitle(true, false); // Hello World - * echo $tag->renderTitle(false, false); // World - * - * - * - * {{ render_title() }} - * - */ - public function renderTitle(bool $prepend = true, bool $append = true) : string - { - } - - /** - * Builds a HTML input[type="reset"] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->reset('Reset') - * - * - * Volt syntax: - * - * {{ reset('Save') }} - * - */ - public function reset(string $name, array $parameters = []) : string - { - } - - /** - * Builds a select element. It accepts an array or a resultset from - * a Phalcon\Mvc\Model - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->select( - * 'status', - * [ - * 'id' => 'status-id', - * 'useEmpty' => true, - * 'emptyValue => '', - * 'emptyText' => 'Choose Status...', - * ], - * [ - * 'A' => 'Active', - * 'I' => 'Inactive', - * ] - * ); - * - * echo $tag->select( - * 'status', - * [ - * 'id' => 'status-id', - * 'useEmpty' => true, - * 'emptyValue => '', - * 'emptyText' => 'Choose Type...', - * 'using' => [ - * 'id, - * 'name', - * ], - * ], - * Robots::find( - * [ - * 'conditions' => 'type = :type:', - * 'bind' => [ - * 'type' => 'mechanical', - * ] - * ] - * ) - * ); - * - * - * - * @param array parameters - * @param array data - */ - public function select(string $name, array $parameters = [], $data = null) : string - { - } - - /** - * Assigns default values to generated tags by helpers - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * // Assigning 'peter' to 'name' component - * $tag->setAttribute('name', 'peter'); - * - * // Later in the view - * echo $tag->inputText('name'); // Will have the value 'peter' by default - * - */ - public function setAttribute(string $name, $value) : Tag - { - } - - /** - * Assigns default values to generated tags by helpers - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * // Assigning 'peter' to 'name' component - * $tag->setAttribute( - * [ - * 'name' => 'peter', - * ] - * ); - * - * // Later in the view - * echo $tag->inputText('name'); // Will have the value 'peter' by default - * - */ - public function setAttributes(array $values, bool $merge = false) : Tag - { - } - - /** - * Sets the dependency injector - */ - public function setDI(DiInterface $container) : void - { - } - - /** - * Set the document type of content - * - * @param int doctype A valid doctype for the content - * - * @return - */ - public function setDocType(int $doctype) : Tag - { - } - - /** - * Set the title separator of view content - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * $tag->setTitle('Phalcon Framework'); - * - */ - public function setTitle(string $title) : Tag - { - } - - /** - * Set the title separator of view content - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->setTitleSeparator('-'); - * - */ - public function setTitleSeparator(string $separator) : Tag - { - } - - /** - * Builds a LINK[rel="stylesheet"] tag - * - * Parameters - * `local` Local resource or not (default `true`) - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * echo $tag->stylesheet( - * 'http://fonts.googleapis.com/css?family=Rosario', - * ['local' => false] - * ); - * echo $tag->stylesheet('css/style.css'); - * - * - * Volt syntax: - * - * {{ stylesheet('http://fonts.googleapis.com/css?family=Rosario', ['local': false]) }} - * {{ stylesheet('css/style.css') }} - * - */ - public function stylesheet(string $url, array $parameters = []) : string - { - } - - /** - * Builds a HTML input[type="submit"] tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - *public - * echo $tag->submit('Save') - * - * - * Volt syntax: - * - * {{ submit('Save') }} - * - */ - public function submit(string $name, array $parameters = []) : string - { - } - - /** - * Builds a HTML TEXTAREA tag - * - * - * use Phalcon\Html\Tag; - * - * $tag = new Tag(); - * - * echo $tag->textArea( - * 'comments', - * [ - * 'cols' => 10, - * 'rows' => 4, - * ] - * ); - * - * - * Volt syntax: - * - * {{ text_area('comments', ['cols': 10, 'rows': 4]) }} - * - */ - public function textArea(string $name, array $parameters = []) : string - { - } - - /** - * Returns the escaper service from the DI container - */ - private function getService(string $name) - { - } - - /** - * Renders the attributes of an HTML element - */ - private function renderAttributes(string $code, array $attributes) : string - { - } - - /** - * Returns the closing tag depending on the doctype - */ - private function renderCloseTag(bool $addEol = false) : string - { - } - - /** - * Builds `input` elements - */ - private function renderInput(string $type, string $name, array $parameters = []) : string - { - } - /** - * Builds INPUT tags that implements the checked attribute - */ - private function renderInputChecked(string $type, string $name, array $parameters = []) : string - { - } - - /** - * Generates the option values or optgroup from an array - */ - private function renderSelectArray(array $options, $value, string $closeOption) : string - { - } - - /** - * Generates the option values from a resultset - */ - private function renderSelectResultset(ResulsetInterface $resultset, $using, $value, string $closeOption) : string - { - } + * + * echo $tag->elementClose( + * [ + * 'name' => 'aside', + * 'useEol' => true, + * ] + * ); // '' . PHP_EOL + * ``` + * + * @param string $tag + * @param array $parameters + * @return string + */ + public function elementClose(string $tag, array $parameters = array()): string {} + + /** + * Returns the closing tag of a form element + * + * @param bool $eol + * @return string + */ + public function endForm(bool $eol = true): string {} + + /** + * Builds a HTML FORM tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tab = new Tag(); + * + * echo $tag->form('posts/save'); + * + * echo $tag->form( + * 'posts/save', + * [ + * "method" => "post", + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ form('posts/save') }}{% endraw %} + * {% raw %}{{ form('posts/save', ['method': 'post') }}{% endraw %} + * ``` + * + * @param string $action + * @param array $parameters + * @return string + */ + public function form(string $action, array $parameters = array()): string {} + + /** + * Converts text to URL-friendly strings + * + * Parameters + * `text` The text to be processed + * `separator` Separator to use (default '-') + * `lowercase` Convert to lowercase + * `replace` + * + * ```php + * use Phalcon\Html\Tag; + * + * $tab = new Tag(); + * + * echo $tag->friendlyTitle( + * [ + * 'text' => 'These are big important news', + * 'separator' => '-', + * ] + * ); + * ``` + * + * Volt Syntax: + * ```php + * {% raw %}{{ friendly_title(['text': 'These are big important news', 'separator': '-']) }}{% endraw %} + * ``` + * + * @param string $text + * @param array $parameters + * @return string + */ + public function friendlyTitle(string $text, array $parameters = array()): string {} + + /** + * Returns the internal dependency injector + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Get the document type declaration of content. If the docType has not + * been set properly, XHTML5 is returned + * + * @return string + */ + public function getDocType(): string {} + + /** + * Gets the current document title. The title will be automatically escaped. + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * $tag + * ->setTitleSeparator(' ') + * ->prependTitle(['Hello']) + * ->setTitle('World') + * ->appendTitle(['from Phalcon']); + * + * echo $tag->getTitle(); // Hello World from Phalcon + * echo $tag->getTitle(false); // World from Phalcon + * echo $tag->getTitle(true, false); // Hello World + * echo $tag->getTitle(false, false); // World + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ get_title() }}{% endraw %} + * ``` + * + * @param bool $prepend + * @param bool $append + * @return string + */ + public function getTitle(bool $prepend = true, bool $append = true): string {} + + /** + * Gets the current document title separator + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->getTitleSeparator(); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ get_title_separator() }}{% endraw %} + * ``` + * + * @return string + */ + public function getTitleSeparator(): string {} + + /** + * Every helper calls this function to check whether a component has a + * predefined value using `setAttribute` or value from $_POST + * + * @param string $name + * @param array $parameters + * @return mixed|null + */ + public function getValue(string $name, array $parameters = array()): ? {} + + /** + * Check if a helper has a default value set using `setAttribute()` or + * value from $_POST + * + * @param string $name + * @return bool + */ + public function hasValue(string $name): bool {} + + /** + * Builds HTML IMG tags + * + * Parameters + * `local` Local resource or not (default `true`) + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->image('img/bg.png'); + * + * echo $tag->image( + * 'img/photo.jpg', + * [ + * 'alt' => 'Some Photo', + * ] + * ); + * + * echo $tag->image( + * 'http://static.mywebsite.com/img/bg.png', + * [ + * 'local' => false, + * ] + * ); + * ``` + * + * Volt Syntax: + * ```php + * {% raw %}{{ image('img/bg.png') }}{% endraw %} + * {% raw %}{{ image('img/photo.jpg', ['alt': 'Some Photo') }}{% endraw %} + * {% raw %}{{ image('http://static.mywebsite.com/img/bg.png', ['local': false]) }}{% endraw %} + * ``` + * + * @param string $url + * @param array $parameters + * @return string + */ + public function image(string $url = '', array $parameters = array()): string {} + + /** + * Builds a HTML input[type="check"] tag + * + * ```php + * echo $tag->inputCheckbox( + * [ + * 'name' => 'terms, + * 'value' => 'Y', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_checkbox(['name': 'terms, 'value': 'Y']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputCheckbox(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='color'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputColor(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='date'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputDate( + * [ + * 'name' => 'born', + * 'value' => '14-12-1980', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_date(['name':'born', 'value':'14-12-1980']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputDate(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='datetime'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputDateTime( + * [ + * 'name' => 'born', + * 'value' => '14-12-1980', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_date_time(['name':'born', 'value':'14-12-1980']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputDateTime(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='datetime-local'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputDateTimeLocal( + * [ + * 'name' => 'born', + * 'value' => '14-12-1980', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_date_time_local(['name':'born', 'value':'14-12-1980']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputDateTimeLocal(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='email'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputEmail( + * [ + * 'name' => 'email', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_email(['name': 'email']);{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputEmail(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='file'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputFile( + * [ + * 'name' => 'file', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_file(['name': 'file']){% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputFile(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='hidden'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputHidden( + * [ + * 'name' => 'my-field', + * 'value' => 'mike', + * ] + * ); + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputHidden(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type="image"] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * echo $tag->inputImage( + * [ + * 'src' => '/img/button.png', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_image(['src': '/img/button.png']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputImage(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='month'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputMonth(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='number'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->numericField( + * [ + * 'name' => 'price', + * 'min' => '1', + * 'max' => '5', + * ] + * ); + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputNumeric(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='password'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->passwordField( + * [ + * 'name' => 'my-field', + * 'size' => 30, + * ] + * ); + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputPassword(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type="radio"] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputRadio( + * [ + * 'name' => 'weather', + * 'value" => 'hot', + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ input_radio(['name': 'weather', 'value": 'hot']) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputRadio(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='range'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputRange(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='search'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputSearch(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='tel'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputTel(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='text'] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->inputText( + * [ + * 'name' => 'my-field', + * 'size' => 30, + * ] + * ); + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputText(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='time'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputTime(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='url'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputUrl(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML input[type='week'] tag + * + * @param string $name + * @param array $parameters + * @return string + */ + public function inputWeek(string $name, array $parameters = array()): string {} + + /** + * Builds a script[type="javascript"] tag + * + * Parameters + * `local` Local resource or not (default `true`) + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->javascript( + * 'http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js', + * [ + * 'local' => false, + * ] + * ); + * + * echo $tag->javascript('javascript/jquery.js'); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ javascript('http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js', ['local': false]) }}{% endraw %} + * {% raw %}{{ javascript('javascript/jquery.js') }}{% endraw %} + * ``` + * + * @param string $url + * @param array $parameters + * @return string + */ + public function javascript(string $url, array $parameters = array()): string {} + + /** + * Builds a HTML A tag using framework conventions + * + * Parameters + * `local` Local resource or not (default `true`) + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->link('signup/register', 'Register Here!'); + * + * echo $tag->link( + * 'signup/register', + * 'Register Here!', + * [ + * 'class' => 'btn-primary', + * ] + * ); + * + * echo $tag->link( + * 'https://phalconphp.com/', + * 'Phalcon!', + * [ + * 'local' => false, + * ] + * ); + * + * echo $tag->link( + * 'https://phalconphp.com/', + * 'Phalcon!', + * [ + * 'local' => false, + * 'target' => '_new', + * ] + * ); + * ``` + * + * @param string $url + * @param string $text + * @param array $parameters + * @return string + */ + public function link(string $url, string $text = '', array $parameters = array()): string {} + + /** + * Prepends a text to current document title + * + * @param mixed $title + * @return Tag + */ + public function prependTitle($title): Tag {} + + /** + * Renders the title with title tags. The title is automaticall escaped + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * $tag + * ->setTitleSeparator(' ') + * ->prependTitle(['Hello']) + * ->setTitle('World') + * ->appendTitle(['from Phalcon']); + * + * echo $tag->renderTitle(); // Hello World from Phalcon + * echo $tag->renderTitle(false); // World from Phalcon + * echo $tag->renderTitle(true, false); // Hello World + * echo $tag->renderTitle(false, false); // World + * ``` + * + * ```php + * {% raw %}{{ render_title() }}{% endraw %} + * ``` + * + * @param bool $prepend + * @param bool $append + * @return string + */ + public function renderTitle(bool $prepend = true, bool $append = true): string {} + + /** + * Builds a HTML input[type="reset"] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->reset('Reset') + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ reset('Save') }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function reset(string $name, array $parameters = array()): string {} + + /** + * Builds a select element. It accepts an array or a resultset from + * a Phalcon\Mvc\Model + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->select( + * 'status', + * [ + * 'id' => 'status-id', + * 'useEmpty' => true, + * 'emptyValue => '', + * 'emptyText' => 'Choose Status...', + * ], + * [ + * 'A' => 'Active', + * 'I' => 'Inactive', + * ] + * ); + * + * echo $tag->select( + * 'status', + * [ + * 'id' => 'status-id', + * 'useEmpty' => true, + * 'emptyValue => '', + * 'emptyText' => 'Choose Type...', + * 'using' => [ + * 'id, + * 'name', + * ], + * ], + * Robots::find( + * [ + * 'conditions' => 'type = :type:', + * 'bind' => [ + * 'type' => 'mechanical', + * ] + * ] + * ) + * ); + * ``` + * + * @param string $name + * @param array $parameters + * @param mixed $data + * @return string + */ + public function select(string $name, array $parameters = array(), $data = null): string {} + + /** + * Assigns default values to generated tags by helpers + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * // Assigning 'peter' to 'name' component + * $tag->setAttribute('name', 'peter'); + * + * // Later in the view + * echo $tag->inputText('name'); // Will have the value 'peter' by default + * ``` + * + * @param string $name + * @param mixed $value + * @return Tag + */ + public function setAttribute(string $name, $value): Tag {} + + /** + * Assigns default values to generated tags by helpers + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * // Assigning 'peter' to 'name' component + * $tag->setAttribute( + * [ + * 'name' => 'peter', + * ] + * ); + * + * // Later in the view + * echo $tag->inputText('name'); // Will have the value 'peter' by default + * ``` + * + * @param array $values + * @param bool $merge + * @return Tag + */ + public function setAttributes(array $values, bool $merge = false): Tag {} + + /** + * Sets the dependency injector + * + * @param \Phalcon\Di\DiInterface $container + */ + public function setDI(\Phalcon\Di\DiInterface $container) {} + + /** + * Set the document type of content + * + * @param int $doctype + * @return Tag + */ + public function setDocType(int $doctype): Tag {} + + /** + * Set the title separator of view content + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * $tag->setTitle('Phalcon Framework'); + * ``` + * + * @param string $title + * @return Tag + */ + public function setTitle(string $title): Tag {} + + /** + * Set the title separator of view content + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->setTitleSeparator('-'); + * ``` + * + * @param string $separator + * @return Tag + */ + public function setTitleSeparator(string $separator): Tag {} + + /** + * Builds a LINK[rel="stylesheet"] tag + * + * Parameters + * `local` Local resource or not (default `true`) + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->stylesheet( + * 'http://fonts.googleapis.com/css?family=Rosario', + * [ + * 'local' => false, + * ] + * ); + * + * echo $tag->stylesheet('css/style.css'); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ stylesheet('http://fonts.googleapis.com/css?family=Rosario', ['local': false]) }}{% endraw %} + * {% raw %}{{ stylesheet('css/style.css') }}{% endraw %} + * ``` + * + * @param string $url + * @param array $parameters + * @return string + */ + public function stylesheet(string $url, array $parameters = array()): string {} + + /** + * Builds a HTML input[type="submit"] tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->submit('Save'); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ submit('Save') }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function submit(string $name, array $parameters = array()): string {} + + /** + * Builds a HTML TEXTAREA tag + * + * ```php + * use Phalcon\Html\Tag; + * + * $tag = new Tag(); + * + * echo $tag->textArea( + * 'comments', + * [ + * 'cols' => 10, + * 'rows' => 4, + * ] + * ); + * ``` + * + * Volt syntax: + * ```php + * {% raw %}{{ text_area('comments', ['cols': 10, 'rows': 4]) }}{% endraw %} + * ``` + * + * @param string $name + * @param array $parameters + * @return string + */ + public function textArea(string $name, array $parameters = array()): string {} + + /** + * Returns the escaper service from the DI container + * + * @param string $name + */ + private function getService(string $name) {} + + /** + * Renders the attributes of an HTML element + * + * @param string $code + * @param array $attributes + * @return string + */ + private function renderAttributes(string $code, array $attributes): string {} + + /** + * Returns the closing tag depending on the doctype + * + * @param bool $addEol + * @return string + */ + private function renderCloseTag(bool $addEol = false): string {} + + /** + * Builds `input` elements + * + * @param string $type + * @param string $name + * @param array $parameters + * @return string + */ + private function renderInput(string $type, string $name, array $parameters = array()): string {} + + /** + * Builds INPUT tags that implements the checked attribute + * + * @param string $type + * @param string $name + * @param array $parameters + * @return string + */ + private function renderInputChecked(string $type, string $name, array $parameters = array()): string {} + + /** + * Generates the option values or optgroup from an array + * + * @param array $options + * @param mixed $value + * @param string $closeOption + * @return string + */ + private function renderSelectArray(array $options, $value, string $closeOption): string {} + + /** + * Generates the option values from a resultset + * + * @param ResulsetInterface $resultset + * @param mixed $using + * @param mixed $value + * @param string $closeOption + * @return string + */ + private function renderSelectResultset(ResulsetInterface $resultset, $using, $value, string $closeOption): string {} + } diff --git a/src/Phalcon/html/TagFactory.php b/src/Phalcon/html/TagFactory.php new file mode 100644 index 00000000..3621c52c --- /dev/null +++ b/src/Phalcon/html/TagFactory.php @@ -0,0 +1,38 @@ + + */ + private $escaper; + + + /** + * TagFactory constructor. + * + * @param \Phalcon\Escaper\EscaperInterface $escaper + * @param array $services + */ + public function __construct(\Phalcon\Escaper\EscaperInterface $escaper, array $services = array()) {} + + /** + * @param string name + * + * @throws Exception + * @param string $name + * @return mixed + */ + public function newInstance(string $name) {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/html/Taglocator.php b/src/Phalcon/html/Taglocator.php deleted file mode 100644 index 2cebb261..00000000 --- a/src/Phalcon/html/Taglocator.php +++ /dev/null @@ -1,14 +0,0 @@ - + */ + protected $escaper; + + + /** + * Constructor + * + * @param \Phalcon\Escaper\EscaperInterface $escaper + */ + public function __construct(\Phalcon\Escaper\EscaperInterface $escaper) {} + + /** + * Renders an element + * + * @param string $tag + * @param string $text + * @param array $attributes + * @param bool $raw + * @return string + */ + protected function renderFullElement(string $tag, string $text, array $attributes = array(), bool $raw = false): string {} + + /** + * Renders an element + * + * @param string $tag + * @param array $attributes + * @return string + */ + protected function renderElement(string $tag, array $attributes = array()): string {} + + /** + * Keeps all the attributes sorted - same order all the tome + * + * @param array attributes + * + * @param array $overrides + * @param array $attributes + * @return array + */ + protected function orderAttributes(array $overrides, array $attributes): array {} + + /** + * Renders all the attributes + * + * @param array $attributes + * @return string + */ + protected function renderAttributes(array $attributes): string {} + + /** + * Produces a self close tag i.e. + * + * @param string $tag + * @param array $attributes + * @return string + */ + protected function selfClose(string $tag, array $attributes = array()): string {} + +} diff --git a/src/Phalcon/html/helper/Abstracthelper.php b/src/Phalcon/html/helper/Abstracthelper.php deleted file mode 100644 index cf39440c..00000000 --- a/src/Phalcon/html/helper/Abstracthelper.php +++ /dev/null @@ -1,54 +0,0 @@ - - */ - protected $escaper; - - /** - * Constructor - */ - public function __construct(EscaperInterface $escaper) - { - } - - /** - * Keeps all the attributes sorted - same order all the tome - */ - protected function orderAttributes(array $overrides, array $attributes) : array - { - } - - /** - * Renders all the attributes - */ - protected function renderAttributes(array $attributes) : string - { - } - - /** - * Renders an element - */ - protected function renderElement(string $tag, string $text, array $attributes = []) - { - } - - /** - * Produces a self close tag i.e. - */ - protected function selfClose(string $tag, array $attributes = []) - { - } -} diff --git a/src/Phalcon/html/helper/Anchor.php b/src/Phalcon/html/helper/Anchor.php index b4ecb01d..5e8646d1 100644 --- a/src/Phalcon/html/helper/Anchor.php +++ b/src/Phalcon/html/helper/Anchor.php @@ -2,21 +2,20 @@ namespace Phalcon\Html\Helper; -use Phalcon\Html\Helper\AbstractHelper; - /** * Phalcon\Html\Helper\Anchor * * Creates an anchor */ -class Anchor extends AbstractHelper +class Anchor extends \Phalcon\Html\Helper\AbstractHelper { - /** - * @var string href The href tag - * @var string text The text for the anchor - * @var array attributes Any additional attributes - */ - public function __invoke(string $href, string $text, array $attributes = []) : string - { - } + + /** + * @param string $href + * @param string $text + * @param array $attributes + * @return string + */ + public function __invoke(string $href, string $text, array $attributes = array()): string {} + } diff --git a/src/Phalcon/html/helper/AnchorRaw.php b/src/Phalcon/html/helper/AnchorRaw.php new file mode 100644 index 00000000..1bdb84b7 --- /dev/null +++ b/src/Phalcon/html/helper/AnchorRaw.php @@ -0,0 +1,21 @@ + + * ```php * use Phalcon\Http\Request; * * $request = new Request(); @@ -19,65 +18,67 @@ * echo "Request was made using POST and AJAX"; * } * - * $request->getServer("HTTP_HOST"); // Retrieve SERVER variables - * $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - * $request->getLanguages(); // An array of languages the client accepts - * + * // Retrieve SERVER variables + * $request->getServer("HTTP_HOST"); + * + * // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + * $request->getMethod(); + * + * // An array of languages the client accepts + * $request->getLanguages(); + * ``` */ class Request implements \Phalcon\Http\RequestInterface, \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; - - - protected $_rawBody; - - - protected $_filter; + private $container; - protected $_putCache; + private $filterService; + /** + * @var bool + */ + private $httpMethodParameterOverride = false; - protected $_httpMethodParameterOverride = false; - + /** + * @var array + */ + private $queryFilters = array(); - protected $_strictHostCheck = false; + private $putCache; - public function getHttpMethodParameterOverride() {} + private $rawBody; /** - * @param mixed $httpMethodParameterOverride + * @var bool */ - public function setHttpMethodParameterOverride($httpMethodParameterOverride) {} + private $strictHostCheck = false; + /** - * Sets the dependency injector - * - * @param \Phalcon\DiInterface $dependencyInjector + * @return bool */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function getHttpMethodParameterOverride(): bool {} /** - * Returns the internal dependency injector - * - * @return \Phalcon\DiInterface + * @param bool $httpMethodParameterOverride */ - public function getDI() {} + public function setHttpMethodParameterOverride(bool $httpMethodParameterOverride) {} /** - * Gets a variable from the $_REQUEST superglobal applying filters if needed. - * If no parameters are given the $_REQUEST superglobal is returned + * Gets a variable from the $_REQUEST superglobal applying filters if + * needed. If no parameters are given the $_REQUEST superglobal is returned * - * + * ```php * // Returns value from $_REQUEST["user_email"] without sanitizing * $userEmail = $request->get("user_email"); * * // Returns value from $_REQUEST["user_email"] with sanitizing * $userEmail = $request->get("user_email", "email"); - * + * ``` * * @param string $name * @param mixed $filters @@ -86,142 +87,120 @@ public function getDI() {} * @param bool $noRecursive * @return mixed */ - public function get($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) {} + public function get(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** - * Gets a variable from the $_POST superglobal applying filters if needed - * If no parameters are given the $_POST superglobal is returned + * Gets an array with mime/types and their quality accepted by the + * browser/client from _SERVER["HTTP_ACCEPT"] * - * - * // Returns value from $_POST["user_email"] without sanitizing - * $userEmail = $request->getPost("user_email"); - * - * // Returns value from $_POST["user_email"] with sanitizing - * $userEmail = $request->getPost("user_email", "email"); - * - * - * @param string $name - * @param mixed $filters - * @param mixed $defaultValue - * @param bool $notAllowEmpty - * @param bool $noRecursive - * @return mixed + * @return array */ - public function getPost($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) {} + public function getAcceptableContent(): array {} /** - * Gets a variable from put request - * - * - * // Returns value from $_PUT["user_email"] without sanitizing - * $userEmail = $request->getPut("user_email"); + * Gets auth info accepted by the browser/client from + * $_SERVER["PHP_AUTH_USER"] * - * // Returns value from $_PUT["user_email"] with sanitizing - * $userEmail = $request->getPut("user_email", "email"); - * - * - * @param string $name - * @param mixed $filters - * @param mixed $defaultValue - * @param bool $notAllowEmpty - * @param bool $noRecursive - * @return mixed + * @return array|null */ - public function getPut($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) {} + public function getBasicAuth(): ?array {} /** - * Gets variable from $_GET superglobal applying filters if needed - * If no parameters are given the $_GET superglobal is returned + * Gets best mime/type accepted by the browser/client from + * _SERVER["HTTP_ACCEPT"] * - * - * // Returns value from $_GET["id"] without sanitizing - * $id = $request->getQuery("id"); - * - * // Returns value from $_GET["id"] with sanitizing - * $id = $request->getQuery("id", "int"); + * @return string + */ + public function getBestAccept(): string {} + + /** + * Gets best charset accepted by the browser/client from + * _SERVER["HTTP_ACCEPT_CHARSET"] * - * // Returns value from $_GET["id"] with a default value - * $id = $request->getQuery("id", null, 150); - * + * @return string + */ + public function getBestCharset(): string {} + + /** + * Gets best language accepted by the browser/client from + * _SERVER["HTTP_ACCEPT_LANGUAGE"] * - * @param string $name - * @param mixed $filters - * @param mixed $defaultValue - * @param bool $notAllowEmpty - * @param bool $noRecursive - * @return mixed + * @return string */ - public function getQuery($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) {} + public function getBestLanguage(): string {} /** - * Helper to get data from superglobals, applying filters if needed. - * If no parameters are given the superglobal is returned. + * Gets most possible client IPv4 Address. This method searches in + * `$_SERVER["REMOTE_ADDR"]` and optionally in + * `$_SERVER["HTTP_X_FORWARDED_FOR"]` * - * @param array $source - * @param string $name - * @param mixed $filters - * @param mixed $defaultValue - * @param bool $notAllowEmpty - * @param bool $noRecursive - * @return mixed + * @param bool $trustForwardedHeader + * @return string|bool */ - protected final function getHelper(array $source, $name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) {} + public function getClientAddress(bool $trustForwardedHeader = false) {} /** - * Gets variable from $_SERVER superglobal + * Gets a charsets array and their quality accepted by the browser/client + * from _SERVER["HTTP_ACCEPT_CHARSET"] * - * @param string $name - * @return string|null + * @return array */ - public function getServer($name) {} + public function getClientCharsets(): array {} /** - * Checks whether $_REQUEST superglobal has certain index + * Gets content type which request has been made * - * @param string $name - * @return bool + * @return string|null */ - public function has($name) {} + public function getContentType(): ?string {} /** - * Checks whether $_POST superglobal has certain index + * Returns the internal dependency injector * - * @param string $name - * @return bool + * @return \Phalcon\Di\DiInterface */ - public function hasPost($name) {} + public function getDI(): DiInterface {} /** - * Checks whether the PUT data has certain index + * Gets auth info accepted by the browser/client from + * $_SERVER["PHP_AUTH_DIGEST"] * - * @param string $name - * @return bool + * @return array */ - public function hasPut($name) {} + public function getDigestAuth(): array {} /** - * Checks whether $_GET superglobal has certain index + * Retrieves a query/get value always sanitized with the preset filters * * @param string $name - * @return bool + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed */ - public function hasQuery($name) {} + public function getFilteredQuery(string $name = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** - * Checks whether $_SERVER superglobal has certain index + * Retrieves a post value always sanitized with the preset filters * * @param string $name - * @return bool + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed */ - public final function hasServer($name) {} + public function getFilteredPost(string $name = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** - * Checks whether headers has certain index + * Retrieves a put value always sanitized with the preset filters * - * @param string $header - * @return bool + * @param string $name + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed */ - public final function hasHeader($header) {} + public function getFilteredPut(string $name = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** * Gets HTTP header from request data @@ -229,58 +208,70 @@ public final function hasHeader($header) {} * @param string $header * @return string */ - public final function getHeader($header) {} + final public function getHeader(string $header): string {} /** - * Gets HTTP schema (http/https) + * Returns the available headers in the request * - * @return string - */ - public function getScheme() {} - - /** - * Checks whether request has been made using ajax + * + * $_SERVER = [ + * "PHP_AUTH_USER" => "phalcon", + * "PHP_AUTH_PW" => "secret", + * ]; * - * @return bool - */ - public function isAjax() {} - - /** - * Checks whether request has been made using SOAP + * $headers = $request->getHeaders(); * - * @return bool - */ - public function isSoap() {} - - /** - * Alias of isSoap(). It will be deprecated in future versions + * echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= + * * - * @deprecated - * @return bool + * @return array */ - public function isSoapRequested() {} + public function getHeaders(): array {} /** - * Checks whether request has been made using any secure layer + * Gets host name used by the request. * - * @return bool - */ - public function isSecure() {} - - /** - * Alias of isSecure(). It will be deprecated in future versions + * `Request::getHttpHost` trying to find host name in following order: * - * @deprecated - * @return bool + * - `$_SERVER["HTTP_HOST"]` + * - `$_SERVER["SERVER_NAME"]` + * - `$_SERVER["SERVER_ADDR"]` + * + * Optionally `Request::getHttpHost` validates and clean host name. + * The `Request::$strictHostCheck` can be used to validate host name. + * + * Note: validation and cleaning have a negative performance impact because + * they use regular expressions. + * + * ```php + * use Phalcon\Http\Request; + * + * $request = new Request; + * + * $_SERVER["HTTP_HOST"] = "example.com"; + * $request->getHttpHost(); // example.com + * + * $_SERVER["HTTP_HOST"] = "example.com:8080"; + * $request->getHttpHost(); // example.com:8080 + * + * $request->setStrictHostCheck(true); + * $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + * $request->getHttpHost(); // UnexpectedValueException + * + * $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + * $request->getHttpHost(); // example.com + * ``` + * + * @return string */ - public function isSecureRequest() {} + public function getHttpHost(): string {} /** - * Gets HTTP raw request body + * Gets web page that refers active request. ie: http://www.google.com * * @return string */ - public function getRawBody() {} + public function getHTTPReferer(): string {} /** * Gets decoded JSON HTTP raw request body @@ -288,357 +279,445 @@ public function getRawBody() {} * @param bool $associative * @return array|bool|\stdClass */ - public function getJsonRawBody($associative = false) {} + public function getJsonRawBody(bool $associative = false) {} /** - * Gets active server address IP + * Gets languages array and their quality accepted by the browser/client + * from _SERVER["HTTP_ACCEPT_LANGUAGE"] * - * @return string + * @return array */ - public function getServerAddress() {} + public function getLanguages(): array {} /** - * Gets active server name + * Gets HTTP method which request has been made + * + * If the X-HTTP-Method-Override header is set, and if the method is a POST, + * then it is used to determine the "real" intended HTTP method. + * + * The _method request parameter can also be used to determine the HTTP + * method, but only if setHttpMethodParameterOverride(true) has been called. + * + * The method is always an uppercased string. * * @return string */ - public function getServerName() {} + final public function getMethod(): string {} /** - * Gets host name used by the request. + * Gets information about the port on which the request is made. * - * `Request::getHttpHost` trying to find host name in following order: + * @return int + */ + public function getPort(): int {} + + /** + * Gets a variable from the $_POST superglobal applying filters if needed + * If no parameters are given the $_POST superglobal is returned * - * - `$_SERVER["HTTP_HOST"]` - * - `$_SERVER["SERVER_NAME"]` - * - `$_SERVER["SERVER_ADDR"]` + * ```php + * // Returns value from $_POST["user_email"] without sanitizing + * $userEmail = $request->getPost("user_email"); * - * Optionally `Request::getHttpHost` validates and clean host name. - * The `Request::$_strictHostCheck` can be used to validate host name. + * // Returns value from $_POST["user_email"] with sanitizing + * $userEmail = $request->getPost("user_email", "email"); + * ``` * - * Note: validation and cleaning have a negative performance impact because - * they use regular expressions. + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed + */ + public function getPost(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} + + /** + * Gets a variable from put request * - * - * use Phalcon\Http\Request; + * ```php + * // Returns value from $_PUT["user_email"] without sanitizing + * $userEmail = $request->getPut("user_email"); * - * $request = new Request; + * // Returns value from $_PUT["user_email"] with sanitizing + * $userEmail = $request->getPut("user_email", "email"); + * ``` * - * $_SERVER["HTTP_HOST"] = "example.com"; - * $request->getHttpHost(); // example.com + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed + */ + public function getPut(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} + + /** + * Gets variable from $_GET superglobal applying filters if needed + * If no parameters are given the $_GET superglobal is returned * - * $_SERVER["HTTP_HOST"] = "example.com:8080"; - * $request->getHttpHost(); // example.com:8080 + * ```php + * // Returns value from $_GET["id"] without sanitizing + * $id = $request->getQuery("id"); * - * $request->setStrictHostCheck(true); - * $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; - * $request->getHttpHost(); // UnexpectedValueException + * // Returns value from $_GET["id"] with sanitizing + * $id = $request->getQuery("id", "int"); * - * $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; - * $request->getHttpHost(); // example.com - * + * // Returns value from $_GET["id"] with a default value + * $id = $request->getQuery("id", null, 150); + * ``` * - * @return string + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed */ - public function getHttpHost() {} + public function getQuery(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** - * Sets if the `Request::getHttpHost` method must be use strict validation of host name or not + * Gets HTTP raw request body * - * @param bool $flag - * @return Request + * @return string */ - public function setStrictHostCheck($flag = true) {} + public function getRawBody(): string {} /** - * Checks if the `Request::getHttpHost` method will be use strict validation of host name or not + * Gets HTTP schema (http/https) * - * @return bool + * @return string */ - public function isStrictHostCheck() {} + public function getScheme(): string {} /** - * Gets information about the port on which the request is made. + * Gets variable from $_SERVER superglobal * - * @return int + * @param string $name + * @return string|null */ - public function getPort() {} + public function getServer(string $name): ?string {} /** - * Gets HTTP URI which request has been made + * Gets active server address IP * * @return string */ - public final function getURI() {} + public function getServerAddress(): string {} /** - * Gets most possible client IPv4 Address. This method searches in - * $_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] + * Gets active server name * - * @param bool $trustForwardedHeader - * @return string|bool + * @return string */ - public function getClientAddress($trustForwardedHeader = false) {} + public function getServerName(): string {} /** - * Gets HTTP method which request has been made - * - * If the X-HTTP-Method-Override header is set, and if the method is a POST, - * then it is used to determine the "real" intended HTTP method. - * - * The _method request parameter can also be used to determine the HTTP method, - * but only if setHttpMethodParameterOverride(true) has been called. + * Gets attached files as Phalcon\Http\Request\File instances * - * The method is always an uppercased string. + * @param bool $onlySuccessful + * @param bool $namedKeys + * @return array|\Phalcon\Http\Request\FileInterface[] + */ + public function getUploadedFiles(bool $onlySuccessful = false, bool $namedKeys = false): array {} + + /** + * Gets HTTP URI which request has been made * * @return string */ - public final function getMethod() {} + final public function getURI(): string {} /** * Gets HTTP user agent used to made the request * * @return string */ - public function getUserAgent() {} + public function getUserAgent(): string {} /** - * Checks if a method is a valid HTTP method + * Checks whether $_REQUEST superglobal has certain index * - * @param string $method + * @param string $name * @return bool */ - public function isValidHttpMethod($method) {} + public function has(string $name): bool {} /** - * Check if HTTP method match any of the passed methods - * When strict is true it checks if validated methods are real HTTP methods + * Returns the number of files available * - * @param mixed $methods - * @param bool $strict + * TODO: Check this + * + * @param bool $onlySuccessful + * @return long + */ + public function hasFiles(bool $onlySuccessful = false): int {} + + /** + * Checks whether headers has certain index + * + * @param string $header * @return bool */ - public function isMethod($methods, $strict = false) {} + final public function hasHeader(string $header): bool {} /** - * Checks whether HTTP method is POST. if _SERVER["REQUEST_METHOD"]==="POST" + * Checks whether $_POST superglobal has certain index * + * @param string $name * @return bool */ - public function isPost() {} + public function hasPost(string $name): bool {} /** - * Checks whether HTTP method is GET. if _SERVER["REQUEST_METHOD"]==="GET" + * Checks whether the PUT data has certain index * + * @param string $name * @return bool */ - public function isGet() {} + public function hasPut(string $name): bool {} /** - * Checks whether HTTP method is PUT. if _SERVER["REQUEST_METHOD"]==="PUT" + * Checks whether $_GET superglobal has certain index * + * @param string $name * @return bool */ - public function isPut() {} + public function hasQuery(string $name): bool {} /** - * Checks whether HTTP method is PATCH. if _SERVER["REQUEST_METHOD"]==="PATCH" + * Checks whether $_SERVER superglobal has certain index * + * @param string $name * @return bool */ - public function isPatch() {} + final public function hasServer(string $name): bool {} /** - * Checks whether HTTP method is HEAD. if _SERVER["REQUEST_METHOD"]==="HEAD" + * Checks whether request has been made using ajax * * @return bool */ - public function isHead() {} + public function isAjax(): bool {} /** - * Checks whether HTTP method is DELETE. if _SERVER["REQUEST_METHOD"]==="DELETE" + * Checks whether HTTP method is CONNECT. + * if _SERVER["REQUEST_METHOD"]==="CONNECT" * * @return bool */ - public function isDelete() {} + public function isConnect(): bool {} /** - * Checks whether HTTP method is OPTIONS. if _SERVER["REQUEST_METHOD"]==="OPTIONS" + * Checks whether HTTP method is DELETE. + * if _SERVER["REQUEST_METHOD"]==="DELETE" * * @return bool */ - public function isOptions() {} + public function isDelete(): bool {} /** - * Checks whether HTTP method is PURGE (Squid and Varnish support). if _SERVER["REQUEST_METHOD"]==="PURGE" + * Checks whether HTTP method is GET. + * if _SERVER["REQUEST_METHOD"]==="GET" * * @return bool */ - public function isPurge() {} + public function isGet(): bool {} /** - * Checks whether HTTP method is TRACE. if _SERVER["REQUEST_METHOD"]==="TRACE" + * Checks whether HTTP method is HEAD. + * if _SERVER["REQUEST_METHOD"]==="HEAD" * * @return bool */ - public function isTrace() {} + public function isHead(): bool {} /** - * Checks whether HTTP method is CONNECT. if _SERVER["REQUEST_METHOD"]==="CONNECT" + * Check if HTTP method match any of the passed methods + * When strict is true it checks if validated methods are real HTTP methods * + * @param mixed $methods + * @param bool $strict * @return bool */ - public function isConnect() {} + public function isMethod($methods, bool $strict = false): bool {} /** - * Checks whether request include attached files + * Checks whether HTTP method is OPTIONS. + * if _SERVER["REQUEST_METHOD"]==="OPTIONS" * - * @param bool $onlySuccessful - * @return long + * @return bool */ - public function hasFiles($onlySuccessful = false) {} + public function isOptions(): bool {} /** - * Recursively counts file in an array of files + * Checks whether HTTP method is PATCH. + * if _SERVER["REQUEST_METHOD"]==="PATCH" * - * @param mixed $data - * @param bool $onlySuccessful - * @return long + * @return bool */ - protected final function hasFileHelper($data, $onlySuccessful) {} + public function isPatch(): bool {} /** - * Gets attached files as Phalcon\Http\Request\File instances + * Checks whether HTTP method is POST. + * if _SERVER["REQUEST_METHOD"]==="POST" * - * @param bool $onlySuccessful - * @return \Phalcon\Http\Request\FileInterface[] + * @return bool */ - public function getUploadedFiles($onlySuccessful = false) {} + public function isPost(): bool {} /** - * Smooth out $_FILES to have plain array with all files uploaded + * Checks whether HTTP method is PUT. + * if _SERVER["REQUEST_METHOD"]==="PUT" * - * @param array $names - * @param array $types - * @param array $tmp_names - * @param array $sizes - * @param array $errors - * @param string $prefix - * @return array + * @return bool */ - protected final function smoothFiles(array $names, array $types, array $tmp_names, array $sizes, array $errors, $prefix) {} + public function isPut(): bool {} /** - * Returns the available headers in the request + * Checks whether HTTP method is PURGE (Squid and Varnish support). + * if _SERVER["REQUEST_METHOD"]==="PURGE" * - * - * $_SERVER = [ - * "PHP_AUTH_USER" => "phalcon", - * "PHP_AUTH_PW" => "secret", - * ]; + * @return bool + */ + public function isPurge(): bool {} + + /** + * Checks whether request has been made using any secure layer * - * $headers = $request->getHeaders(); + * @return bool + */ + public function isSecure(): bool {} + + /** + * Checks if the `Request::getHttpHost` method will be use strict validation + * of host name or not * - * echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= - * + * @return bool + */ + public function isStrictHostCheck(): bool {} + + /** + * Checks whether request has been made using SOAP * - * @return array + * @return bool */ - public function getHeaders() {} + public function isSoap(): bool {} /** - * Resolve authorization headers. + * Checks whether HTTP method is TRACE. + * if _SERVER["REQUEST_METHOD"]==="TRACE" * - * @return array + * @return bool */ - protected function resolveAuthorizationHeaders() {} + public function isTrace(): bool {} /** - * Gets web page that refers active request. ie: http://www.google.com + * Checks if a method is a valid HTTP method * - * @return string + * @param string $method + * @return bool */ - public function getHTTPReferer() {} + public function isValidHttpMethod(string $method): bool {} /** - * Process a request header and return the one with best quality + * Sets the dependency injector * - * @param array $qualityParts - * @param string $name - * @return string + * @param \Phalcon\Di\DiInterface $container */ - protected final function _getBestQuality(array $qualityParts, $name) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Gets content type which request has been made + * Sets automatic sanitizers/filters for a particular field and for + * particular methods * - * @return string|null + * @param string $name + * @param array $filters + * @param array $scope + * @return RequestInterface */ - public function getContentType() {} + public function setParameterFilters(string $name, array $filters = array(), array $scope = array()): RequestInterface {} /** - * Gets an array with mime/types and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT"] + * Sets if the `Request::getHttpHost` method must be use strict validation + * of host name or not * - * @return array + * @param bool $flag + * @return RequestInterface */ - public function getAcceptableContent() {} + public function setStrictHostCheck(bool $flag = true): RequestInterface {} /** - * Gets best mime/type accepted by the browser/client from _SERVER["HTTP_ACCEPT"] + * Process a request header and return the one with best quality * + * @param array $qualityParts + * @param string $name * @return string */ - public function getBestAccept() {} + final protected function getBestQuality(array $qualityParts, string $name): string {} /** - * Gets a charsets array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"] + * Helper to get data from superglobals, applying filters if needed. + * If no parameters are given the superglobal is returned. * - * @return array + * @param array $source + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed */ - public function getClientCharsets() {} + final protected function getHelper(array $source, string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false) {} /** - * Gets best charset accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"] + * Recursively counts file in an array of files * - * @return string + * @param mixed $data + * @param bool $onlySuccessful + * @return long */ - public function getBestCharset() {} + final protected function hasFileHelper($data, bool $onlySuccessful): int {} /** - * Gets languages array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"] + * Process a request header and return an array of values with their qualities * + * @param string $serverIndex + * @param string $name * @return array */ - public function getLanguages() {} + final protected function getQualityHeader(string $serverIndex, string $name): array {} /** - * Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"] + * Resolve authorization headers. * - * @return string + * @return array */ - public function getBestLanguage() {} + protected function resolveAuthorizationHeaders(): array {} /** - * Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] + * Smooth out $_FILES to have plain array with all files uploaded * - * @return array|null + * @param array $names + * @param array $types + * @param array $tmp_names + * @param array $sizes + * @param array $errors + * @param string $prefix + * @return array */ - public function getBasicAuth() {} + final protected function smoothFiles(array $names, array $types, array $tmp_names, array $sizes, array $errors, string $prefix): array {} /** - * Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + * Checks the filter service and assigns it to the class parameter * - * @return array + * @return \Phalcon\Filter\FilterInterface */ - public function getDigestAuth() {} + private function getFilterService(): FilterInterface {} /** - * Process a request header and return an array of values with their qualities - * - * @param string $serverIndex - * @param string $name * @return array */ - protected final function _getQualityHeader($serverIndex, $name) {} + private function getServerArray(): array {} } diff --git a/src/Phalcon/http/RequestInterface.php b/src/Phalcon/http/RequestInterface.php index 493883ff..853091b0 100644 --- a/src/Phalcon/http/RequestInterface.php +++ b/src/Phalcon/http/RequestInterface.php @@ -3,90 +3,104 @@ namespace Phalcon\Http; /** - * Phalcon\Http\RequestInterface - * * Interface for Phalcon\Http\Request */ interface RequestInterface { /** - * Gets a variable from the $_REQUEST superglobal applying filters if needed + * Gets a variable from the $_REQUEST superglobal applying filters if + * needed. If no parameters are given the $_REQUEST superglobal is returned + * + * ```php + * // Returns value from $_REQUEST["user_email"] without sanitizing + * $userEmail = $request->get("user_email"); + * + * // Returns value from $_REQUEST["user_email"] with sanitizing + * $userEmail = $request->get("user_email", "email"); + * ``` * * @param string $name - * @param string|array $filters + * @param mixed $filters * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive * @return mixed */ - public function get($name = null, $filters = null, $defaultValue = null); + public function get(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false); /** - * Gets a variable from the $_POST superglobal applying filters if needed + * Gets an array with mime/types and their quality accepted by the + * browser/client from _SERVER["HTTP_ACCEPT"] * - * @param string $name - * @param string|array $filters - * @param mixed $defaultValue - * @return mixed + * @return array */ - public function getPost($name = null, $filters = null, $defaultValue = null); + public function getAcceptableContent(): array; /** - * Gets variable from $_GET superglobal applying filters if needed + * Gets auth info accepted by the browser/client from + * $_SERVER["PHP_AUTH_USER"] * - * @param string $name - * @param string|array $filters - * @param mixed $defaultValue - * @return mixed + * @return array|null */ - public function getQuery($name = null, $filters = null, $defaultValue = null); + public function getBasicAuth(): ?array; /** - * Gets variable from $_SERVER superglobal + * Gets best mime/type accepted by the browser/client from + * _SERVER["HTTP_ACCEPT"] * - * @param string $name - * @return mixed + * @return string */ - public function getServer($name); + public function getBestAccept(): string; /** - * Checks whether $_REQUEST superglobal has certain index + * Gets best charset accepted by the browser/client from + * _SERVER["HTTP_ACCEPT_CHARSET"] * - * @param string $name - * @return bool + * @return string */ - public function has($name); + public function getBestCharset(): string; /** - * Checks whether $_POST superglobal has certain index + * Gets best language accepted by the browser/client from + * _SERVER["HTTP_ACCEPT_LANGUAGE"] * - * @param string $name - * @return bool + * @return string */ - public function hasPost($name); + public function getBestLanguage(): string; /** - * Checks whether the PUT data has certain index + * Gets most possible client IPv4 Address. This method searches in + * $_SERVER["REMOTE_ADDR"] and optionally in + * $_SERVER["HTTP_X_FORWARDED_FOR"] * - * @param string $name - * @return bool + * @param bool $trustForwardedHeader + * @return string|bool */ - public function hasPut($name); + public function getClientAddress(bool $trustForwardedHeader = false); /** - * Checks whether $_GET superglobal has certain index + * Gets a charsets array and their quality accepted by the browser/client + * from _SERVER["HTTP_ACCEPT_CHARSET"] * - * @param string $name - * @return bool + * @return array */ - public function hasQuery($name); + public function getClientCharsets(): array; /** - * Checks whether $_SERVER superglobal has certain index + * Gets content type which request has been made * - * @param string $name - * @return bool + * @return string|null + */ + public function getContentType(): ?string; + + /** + * Gets auth info accepted by the browser/client from + * $_SERVER["PHP_AUTH_DIGEST"] + * + * @return array */ - public function hasServer($name); + public function getDigestAuth(): array; /** * Gets HTTP header from request data @@ -94,243 +108,383 @@ public function hasServer($name); * @param string $header * @return string */ - public function getHeader($header); + public function getHeader(string $header): string; /** - * Gets HTTP schema (http/https) + * Returns the available headers in the request + * + * ```php + * $_SERVER = [ + * "PHP_AUTH_USER" => "phalcon", + * "PHP_AUTH_PW" => "secret", + * ]; + * + * $headers = $request->getHeaders(); + * + * echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= + * ``` + * + * @return array + */ + public function getHeaders(): array; + + /** + * Gets host name used by the request. + * + * `Request::getHttpHost` trying to find host name in following order: + * + * - `$_SERVER["HTTP_HOST"]` + * - `$_SERVER["SERVER_NAME"]` + * - `$_SERVER["SERVER_ADDR"]` + * + * Optionally `Request::getHttpHost` validates and clean host name. + * The `Request::$_strictHostCheck` can be used to validate host name. + * + * Note: validation and cleaning have a negative performance impact because + * they use regular expressions. + * + * ```php + * use Phalcon\Http\Request; + * + * $request = new Request; + * + * $_SERVER["HTTP_HOST"] = "example.com"; + * $request->getHttpHost(); // example.com + * + * $_SERVER["HTTP_HOST"] = "example.com:8080"; + * $request->getHttpHost(); // example.com:8080 + * + * $request->setStrictHostCheck(true); + * $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + * $request->getHttpHost(); // UnexpectedValueException + * + * $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + * $request->getHttpHost(); // example.com + * ``` * * @return string */ - public function getScheme(); + public function getHttpHost(): string; /** - * Checks whether request has been made using ajax. Checks if $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest" + * Gets web page that refers active request. ie: http://www.google.com * - * @return bool + * @return string */ - public function isAjax(); + public function getHTTPReferer(): string; /** - * Checks whether request has been made using SOAP + * Gets decoded JSON HTTP raw request body * - * @return bool + * @param bool $associative + * @return array|bool|\stdClass */ - public function isSoapRequested(); + public function getJsonRawBody(bool $associative = false); /** - * Checks whether request has been made using any secure layer + * Gets languages array and their quality accepted by the browser/client + * from _SERVER["HTTP_ACCEPT_LANGUAGE"] * - * @return bool + * @return array */ - public function isSecureRequest(); + public function getLanguages(): array; /** - * Gets HTTP raw request body + * Gets HTTP method which request has been made + * + * If the X-HTTP-Method-Override header is set, and if the method is a POST, + * then it is used to determine the "real" intended HTTP method. + * + * The _method request parameter can also be used to determine the HTTP + * method, but only if setHttpMethodParameterOverride(true) has been called. + * + * The method is always an uppercased string. * * @return string */ - public function getRawBody(); + public function getMethod(): string; /** - * Gets active server address IP + * Gets information about the port on which the request is made * - * @return string + * @return int */ - public function getServerAddress(); + public function getPort(): int; /** - * Gets active server name + * Gets HTTP URI which request has been made * * @return string */ - public function getServerName(); + final public function getURI(): string; + + /** + * Gets a variable from the $_POST superglobal applying filters if needed + * If no parameters are given the $_POST superglobal is returned + * + * ```php + * // Returns value from $_POST["user_email"] without sanitizing + * $userEmail = $request->getPost("user_email"); + * + * // Returns value from $_POST["user_email"] with sanitizing + * $userEmail = $request->getPost("user_email", "email"); + * ``` + * + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed + */ + public function getPost(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false); + + /** + * Gets a variable from put request + * + * ```php + * // Returns value from $_PUT["user_email"] without sanitizing + * $userEmail = $request->getPut("user_email"); + * + * // Returns value from $_PUT["user_email"] with sanitizing + * $userEmail = $request->getPut("user_email", "email"); + * ``` + * + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed + */ + public function getPut(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false); + + /** + * Gets variable from $_GET superglobal applying filters if needed + * If no parameters are given the $_GET superglobal is returned + * + * ```php + * // Returns value from $_GET["id"] without sanitizing + * $id = $request->getQuery("id"); + * + * // Returns value from $_GET["id"] with sanitizing + * $id = $request->getQuery("id", "int"); + * + * // Returns value from $_GET["id"] with a default value + * $id = $request->getQuery("id", null, 150); + * ``` + * + * @param string $name + * @param mixed $filters + * @param mixed $defaultValue + * @param bool $notAllowEmpty + * @param bool $noRecursive + * @return mixed + */ + public function getQuery(string $name = null, $filters = null, $defaultValue = null, bool $notAllowEmpty = false, bool $noRecursive = false); /** - * Gets host name used by the request + * Gets HTTP raw request body * * @return string */ - public function getHttpHost(); + public function getRawBody(): string; /** - * Gets information about the port on which the request is made + * Gets HTTP schema (http/https) * - * @return int + * @return string */ - public function getPort(); + public function getScheme(): string; /** - * Gets most possibly client IPv4 Address. This methods searches in - * $_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] + * Gets variable from $_SERVER superglobal * - * @param bool $trustForwardedHeader - * @return string|bool + * @param string $name + * @return string|null */ - public function getClientAddress($trustForwardedHeader = false); + public function getServer(string $name): ?string; /** - * Gets HTTP method which request has been made + * Gets active server address IP * * @return string */ - public function getMethod(); + public function getServerAddress(): string; /** - * Gets HTTP user agent used to made the request + * Gets active server name * * @return string */ - public function getUserAgent(); + public function getServerName(): string; /** - * Check if HTTP method match any of the passed methods + * Gets attached files as Phalcon\Http\Request\FileInterface compatible + * instances * - * @param string|array $methods - * @param bool $strict - * @return bool + * @param bool $onlySuccessful + * @param bool $namedKeys + * @return array|\Phalcon\Http\Request\FileInterface[] */ - public function isMethod($methods, $strict = false); + public function getUploadedFiles(bool $onlySuccessful = false, bool $namedKeys = false): array; /** - * Checks whether HTTP method is POST. if $_SERVER["REQUEST_METHOD"] === "POST" + * Gets HTTP user agent used to made the request * - * @return bool + * @return string */ - public function isPost(); + public function getUserAgent(): string; /** - * Checks whether HTTP method is GET. if $_SERVER["REQUEST_METHOD"] === "GET" + * Checks whether $_REQUEST superglobal has certain index * + * @param string $name * @return bool */ - public function isGet(); + public function has(string $name): bool; /** - * Checks whether HTTP method is PUT. if $_SERVER["REQUEST_METHOD"] === "PUT" + * Checks whether request include attached files + * TODO: We need to check the name. Not very intuitive + * + * @param bool $onlySuccessful + * @return long + */ + public function hasFiles(bool $onlySuccessful = false): int; + + /** + * Checks whether headers has certain index * + * @param string $header * @return bool */ - public function isPut(); + public function hasHeader(string $header): bool; /** - * Checks whether HTTP method is HEAD. if $_SERVER["REQUEST_METHOD"] === "HEAD" + * Checks whether $_GET superglobal has certain index * + * @param string $name * @return bool */ - public function isHead(); + public function hasQuery(string $name): bool; /** - * Checks whether HTTP method is DELETE. if $_SERVER["REQUEST_METHOD"] === "DELETE" + * Checks whether $_POST superglobal has certain index * + * @param string $name * @return bool */ - public function isDelete(); + public function hasPost(string $name): bool; /** - * Checks whether HTTP method is OPTIONS. if $_SERVER["REQUEST_METHOD"] === "OPTIONS" + * Checks whether the PUT data has certain index * + * @param string $name * @return bool */ - public function isOptions(); + public function hasPut(string $name): bool; /** - * Checks whether HTTP method is PURGE (Squid and Varnish support). if $_SERVER["REQUEST_METHOD"] === "PURGE" + * Checks whether $_SERVER superglobal has certain index * + * @param string $name * @return bool */ - public function isPurge(); + public function hasServer(string $name): bool; /** - * Checks whether HTTP method is TRACE. if $_SERVER["REQUEST_METHOD"] === "TRACE" + * Checks whether request has been made using ajax. Checks if $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest" * * @return bool */ - public function isTrace(); + public function isAjax(): bool; /** * Checks whether HTTP method is CONNECT. if $_SERVER["REQUEST_METHOD"] === "CONNECT" * * @return bool */ - public function isConnect(); + public function isConnect(): bool; /** - * Checks whether request include attached files + * Checks whether HTTP method is DELETE. if $_SERVER["REQUEST_METHOD"] === "DELETE" * - * @param boolean $onlySuccessful - * @return int + * @return bool */ - public function hasFiles($onlySuccessful = false); + public function isDelete(): bool; /** - * Gets attached files as Phalcon\Http\Request\FileInterface compatible instances + * Checks whether HTTP method is GET. if $_SERVER["REQUEST_METHOD"] === "GET" * - * @param bool $onlySuccessful - * @return \Phalcon\Http\Request\FileInterface[] + * @return bool */ - public function getUploadedFiles($onlySuccessful = false); + public function isGet(): bool; /** - * Gets web page that refers active request. ie: http://www.google.com + * Checks whether HTTP method is HEAD. if $_SERVER["REQUEST_METHOD"] === "HEAD" * - * @return string + * @return bool */ - public function getHTTPReferer(); + public function isHead(): bool; /** - * Gets array with mime/types and their quality accepted by the browser/client from $_SERVER["HTTP_ACCEPT"] + * Check if HTTP method match any of the passed methods * - * @return array + * @param string|array $methods + * @param bool $strict + * @return bool */ - public function getAcceptableContent(); + public function isMethod($methods, bool $strict = false): bool; /** - * Gets best mime/type accepted by the browser/client from $_SERVER["HTTP_ACCEPT"] + * Checks whether HTTP method is OPTIONS. if $_SERVER["REQUEST_METHOD"] === "OPTIONS" * - * @return string + * @return bool */ - public function getBestAccept(); + public function isOptions(): bool; /** - * Gets charsets array and their quality accepted by the browser/client from $_SERVER["HTTP_ACCEPT_CHARSET"] + * Checks whether HTTP method is POST. if $_SERVER["REQUEST_METHOD"] === "POST" * - * @return array + * @return bool */ - public function getClientCharsets(); + public function isPost(): bool; /** - * Gets best charset accepted by the browser/client from $_SERVER["HTTP_ACCEPT_CHARSET"] + * Checks whether HTTP method is PURGE (Squid and Varnish support). if $_SERVER["REQUEST_METHOD"] === "PURGE" * - * @return string + * @return bool */ - public function getBestCharset(); + public function isPurge(): bool; /** - * Gets languages array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"] + * Checks whether HTTP method is PUT. if $_SERVER["REQUEST_METHOD"] === "PUT" * - * @return array + * @return bool */ - public function getLanguages(); + public function isPut(): bool; /** - * Gets best language accepted by the browser/client from $_SERVER["HTTP_ACCEPT_LANGUAGE"] + * Checks whether request has been made using any secure layer * - * @return string + * @return bool */ - public function getBestLanguage(); + public function isSecure(): bool; /** - * Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] + * Checks whether request has been made using SOAP * - * @return array + * @return bool */ - public function getBasicAuth(); + public function isSoap(): bool; /** - * Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + * Checks whether HTTP method is TRACE. + * if $_SERVER["REQUEST_METHOD"] === "TRACE" * - * @return array + * @return bool */ - public function getDigestAuth(); + public function isTrace(): bool; } diff --git a/src/Phalcon/http/Response.php b/src/Phalcon/http/Response.php index 31dd3efe..31051ef3 100644 --- a/src/Phalcon/http/Response.php +++ b/src/Phalcon/http/Response.php @@ -3,40 +3,46 @@ namespace Phalcon\Http; /** - * Phalcon\Http\Response - * * Part of the HTTP cycle is return responses to the clients. * Phalcon\HTTP\Response is the Phalcon component responsible to achieve this task. * HTTP responses are usually composed by headers and body. * - * + * ```php * $response = new \Phalcon\Http\Response(); * * $response->setStatusCode(200, "OK"); * $response->setContent("Hello"); * * $response->send(); - * + * ``` */ -class Response implements \Phalcon\Http\ResponseInterface, \Phalcon\Di\InjectionAwareInterface +class Response implements \Phalcon\Http\ResponseInterface, \Phalcon\Di\InjectionAwareInterface, \Phalcon\Events\EventsAwareInterface { - protected $_sent = false; + protected $container; + + protected $content; - protected $_content; + protected $cookies; - protected $_headers; + protected $eventsManager; - protected $_cookies; + protected $file; - protected $_file; + protected $headers; - protected $_dependencyInjector; + /** + * @var bool + */ + protected $sent = false; + + + protected $statusCodes; /** @@ -49,321 +55,351 @@ class Response implements \Phalcon\Http\ResponseInterface, \Phalcon\Di\Injection public function __construct($content = null, $code = null, $status = null) {} /** - * Sets the dependency injector + * Appends a string to the HTTP response body * - * @param \Phalcon\DiInterface $dependencyInjector + * @param mixed $content + * @return ResponseInterface */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function appendContent($content): ResponseInterface {} /** - * Returns the internal dependency injector + * Gets the HTTP response body * - * @return \Phalcon\DiInterface + * @return string */ - public function getDI() {} + public function getContent(): string {} /** - * Sets the HTTP response code + * Returns cookies set by the user * - * - * $response->setStatusCode(404, "Not Found"); - * + * @return \Phalcon\Http\Response\CookiesInterface + */ + public function getCookies(): CookiesInterface {} + + /** + * Returns the internal dependency injector * - * @param int $code - * @param string $message - * @return ResponseInterface + * @return \Phalcon\Di\DiInterface */ - public function setStatusCode($code, $message = null) {} + public function getDI(): DiInterface {} /** - * Returns the status code + * Returns the internal event manager * - * - * echo $response->getStatusCode(); - * + * @return \Phalcon\Events\ManagerInterface + */ + public function getEventsManager(): ManagerInterface {} + + /** + * Returns headers set by the user * - * @return int|null + * @return \Phalcon\Http\Response\HeadersInterface */ - public function getStatusCode() {} + public function getHeaders(): HeadersInterface {} /** * Returns the reason phrase * - * + * ```php * echo $response->getReasonPhrase(); - * + * ``` * * @return string|null */ - public function getReasonPhrase() {} + public function getReasonPhrase(): ?string {} /** - * Sets a headers bag for the response externally + * Returns the status code * - * @param \Phalcon\Http\Response\HeadersInterface $headers - * @return ResponseInterface + * ```php + * echo $response->getStatusCode(); + * ``` + * + * @return int|null */ - public function setHeaders(\Phalcon\Http\Response\HeadersInterface $headers) {} + public function getStatusCode(): ?int {} /** - * Returns headers set by the user + * Checks if a header exists * - * @return \Phalcon\Http\Response\HeadersInterface + * ```php + * $response->hasHeader("Content-Type"); + * ``` + * + * @param string $name + * @return bool */ - public function getHeaders() {} + public function hasHeader(string $name): bool {} /** - * Sets a cookies bag for the response externally + * Check if the response is already sent * - * @param \Phalcon\Http\Response\CookiesInterface $cookies - * @return Response + * @return bool */ - public function setCookies(\Phalcon\Http\Response\CookiesInterface $cookies) {} + public function isSent(): bool {} /** - * Returns cookies set by the user + * Redirect by HTTP to another action or URL * - * @return \Phalcon\Http\Response\CookiesInterface + * ```php + * // Using a string redirect (internal/external) + * $response->redirect("posts/index"); + * $response->redirect("http://en.wikipedia.org", true); + * $response->redirect("http://www.example.com/new-location", true, 301); + * + * // Making a redirection based on a named route + * $response->redirect( + * [ + * "for" => "index-lang", + * "lang" => "jp", + * "controller" => "index", + * ] + * ); + * ``` + * + * @param mixed $location + * @param bool $externalRedirect + * @param int $statusCode + * @return ResponseInterface */ - public function getCookies() {} + public function redirect($location = null, bool $externalRedirect = false, int $statusCode = 302): ResponseInterface {} /** - * Overwrites a header in the response + * Remove a header in the response * - * - * $response->setHeader("Content-Type", "text/plain"); - * + * ```php + * $response->removeHeader("Expires"); + * ``` * * @param string $name - * @param mixed $value * @return ResponseInterface */ - public function setHeader($name, $value) {} + public function removeHeader(string $name): ResponseInterface {} /** - * Send a raw header to the response - * - * - * $response->setRawHeader("HTTP/1.1 404 Not Found"); - * + * Resets all the established headers * - * @param string $header * @return ResponseInterface */ - public function setRawHeader($header) {} + public function resetHeaders(): ResponseInterface {} /** - * Resets all the established headers + * Prints out HTTP response to the client * * @return ResponseInterface */ - public function resetHeaders() {} + public function send(): ResponseInterface {} /** - * Sets an Expires header in the response that allows to use the HTTP cache - * - * - * $this->response->setExpires( - * new DateTime() - * ); - * + * Sends cookies to the client * - * @param \DateTime $datetime * @return ResponseInterface */ - public function setExpires(\DateTime $datetime) {} + public function sendCookies(): ResponseInterface {} /** - * Sets Last-Modified header - * - * - * $this->response->setLastModified( - * new DateTime() - * ); - * + * Sends headers to the client * - * @param \DateTime $datetime - * @return Response + * @return bool|ResponseInterface */ - public function setLastModified(\DateTime $datetime) {} + public function sendHeaders() {} /** * Sets Cache headers to use HTTP cache * - * + * ```php * $this->response->setCache(60); - * + * ``` * * @param int $minutes - * @return Response + * @return ResponseInterface */ - public function setCache($minutes) {} + public function setCache(int $minutes): ResponseInterface {} /** - * Sends a Not-Modified response + * Sets HTTP response body + * + * ```php + * $response->setContent("

Hello!

"); + * ``` + * + * @param string $content + * @return ResponseInterface + */ + public function setContent(string $content): ResponseInterface {} + + /** + * Sets the response content-length * + * ```php + * $response->setContentLength(2048); + * ``` + * + * @param int $contentLength * @return ResponseInterface */ - public function setNotModified() {} + public function setContentLength(int $contentLength): ResponseInterface {} /** * Sets the response content-type mime, optionally the charset * - * + * ```php * $response->setContentType("application/pdf"); * $response->setContentType("text/plain", "UTF-8"); - * + * ``` * * @param string $contentType * @param mixed $charset * @return ResponseInterface */ - public function setContentType($contentType, $charset = null) {} + public function setContentType(string $contentType, $charset = null): ResponseInterface {} /** - * Sets the response content-length - * - * - * $response->setContentLength(2048); - * + * Sets a cookies bag for the response externally * - * @param int $contentLength + * @param \Phalcon\Http\Response\CookiesInterface $cookies * @return ResponseInterface */ - public function setContentLength($contentLength) {} + public function setCookies(\Phalcon\Http\Response\CookiesInterface $cookies): ResponseInterface {} /** - * Set a custom ETag - * - * - * $response->setEtag(md5(time())); - * + * Sets the dependency injector * - * @param string $etag - * @return Response + * @param \Phalcon\Di\DiInterface $container */ - public function setEtag($etag) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Redirect by HTTP to another action or URL - * - * - * // Using a string redirect (internal/external) - * $response->redirect("posts/index"); - * $response->redirect("http://en.wikipedia.org", true); - * $response->redirect("http://www.example.com/new-location", true, 301); + * Set a custom ETag * - * // Making a redirection based on a named route - * $response->redirect( - * [ - * "for" => "index-lang", - * "lang" => "jp", - * "controller" => "index", - * ] + * ```php + * $response->setEtag( + * md5( + * time() + * ) * ); - * + * ``` * - * @param mixed $location - * @param bool $externalRedirect - * @param int $statusCode + * @param string $etag * @return ResponseInterface */ - public function redirect($location = null, $externalRedirect = false, $statusCode = 302) {} + public function setEtag(string $etag): ResponseInterface {} /** - * Sets HTTP response body + * Sets an Expires header in the response that allows to use the HTTP cache * - * - * $response->setContent("

Hello!

"); - *
+ * ```php + * $this->response->setExpires( + * new DateTime() + * ); + * ``` * - * @param string $content + * @param \DateTime $datetime * @return ResponseInterface */ - public function setContent($content) {} + public function setExpires(\DateTime $datetime): ResponseInterface {} /** - * Sets HTTP response body. The parameter is automatically converted to JSON - * and also sets default header: Content-Type: "application/json; charset=UTF-8" + * Sets the events manager * - * - * $response->setJsonContent( - * [ - * "status" => "OK", - * ] - * ); - * - * - * @param mixed $content - * @param int $jsonOptions - * @param int $depth - * @return ResponseInterface + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function setJsonContent($content, $jsonOptions = 0, $depth = 512) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Appends a string to the HTTP response body + * Sets an attached file to be sent at the end of the request * - * @param mixed $content + * @param string $filePath + * @param mixed $attachmentName + * @param mixed $attachment * @return ResponseInterface */ - public function appendContent($content) {} + public function setFileToSend(string $filePath, $attachmentName = null, $attachment = true): ResponseInterface {} /** - * Gets the HTTP response body + * Overwrites a header in the response * - * @return string + * ```php + * $response->setHeader("Content-Type", "text/plain"); + * ``` + * + * @param string $name + * @param mixed $value + * @return ResponseInterface */ - public function getContent() {} + public function setHeader(string $name, $value): ResponseInterface {} /** - * Check if the response is already sent + * Sets a headers bag for the response externally * - * @return bool + * @param \Phalcon\Http\Response\HeadersInterface $headers + * @return ResponseInterface */ - public function isSent() {} + public function setHeaders(\Phalcon\Http\Response\HeadersInterface $headers): ResponseInterface {} /** - * Sends headers to the client + * Sets HTTP response body. The parameter is automatically converted to JSON + * and also sets default header: Content-Type: "application/json; charset=UTF-8" * + * ```php + * $response->setJsonContent( + * [ + * "status" => "OK", + * ] + * ); + * ``` + * + * @param mixed $content + * @param int $jsonOptions + * @param int $depth * @return ResponseInterface */ - public function sendHeaders() {} + public function setJsonContent($content, int $jsonOptions = 0, int $depth = 512): ResponseInterface {} /** - * Sends cookies to the client + * Sets Last-Modified header + * + * ```php + * $this->response->setLastModified( + * new DateTime() + * ); + * ``` * + * @param \DateTime $datetime * @return ResponseInterface */ - public function sendCookies() {} + public function setLastModified(\DateTime $datetime): ResponseInterface {} /** - * Prints out HTTP response to the client + * Sends a Not-Modified response * * @return ResponseInterface */ - public function send() {} + public function setNotModified(): ResponseInterface {} /** - * Sets an attached file to be sent at the end of the request + * Sets the HTTP response code * - * @param string $filePath - * @param mixed $attachmentName - * @param mixed $attachment + * ```php + * $response->setStatusCode(404, "Not Found"); + * ``` + * + * @param int $code + * @param string $message * @return ResponseInterface */ - public function setFileToSend($filePath, $attachmentName = null, $attachment = true) {} + public function setStatusCode(int $code, string $message = null): ResponseInterface {} /** - * Remove a header in the response + * Send a raw header to the response * - * - * $response->removeHeader("Expires"); - * + * ```php + * $response->setRawHeader("HTTP/1.1 404 Not Found"); + * ``` * - * @param string $name - * @return Response + * @param string $header + * @return ResponseInterface */ - public function removeHeader($name) {} + public function setRawHeader(string $header): ResponseInterface {} } diff --git a/src/Phalcon/http/ResponseInterface.php b/src/Phalcon/http/ResponseInterface.php index 17f684bc..d3176976 100644 --- a/src/Phalcon/http/ResponseInterface.php +++ b/src/Phalcon/http/ResponseInterface.php @@ -11,59 +11,81 @@ interface ResponseInterface { /** - * Sets the HTTP response code + * Appends a string to the HTTP response body * - * @param int $code - * @param string $message + * @param mixed $content * @return ResponseInterface */ - public function setStatusCode($code, $message = null); + public function appendContent($content): ResponseInterface; + + /** + * Gets the HTTP response body + * + * @return string + */ + public function getContent(): string; + + /** + * Returns the status code + * + * @return int|null + */ + public function getStatusCode(): ?int; /** * Returns headers set by the user * * @return \Phalcon\Http\Response\HeadersInterface */ - public function getHeaders(); + public function getHeaders(): HeadersInterface; /** - * Overwrites a header in the response + * Checks if a header exists * * @param string $name - * @param mixed $value - * @return ResponseInterface + * @return bool */ - public function setHeader($name, $value); + public function hasHeader(string $name): bool; /** - * Send a raw header to the response + * Checks if the response was already sent * - * @param string $header + * @return bool + */ + public function isSent(): bool; + + /** + * Redirect by HTTP to another action or URL + * + * @param mixed $location + * @param bool $externalRedirect + * @param int $statusCode * @return ResponseInterface */ - public function setRawHeader($header); + public function redirect($location = null, bool $externalRedirect = false, int $statusCode = 302): ResponseInterface; /** * Resets all the established headers * * @return ResponseInterface */ - public function resetHeaders(); + public function resetHeaders(): ResponseInterface; /** - * Sets output expire time header + * Sets HTTP response body * - * @param \DateTime $datetime + * @param string $content * @return ResponseInterface */ - public function setExpires(\DateTime $datetime); + public function setContent(string $content): ResponseInterface; /** - * Sends a Not-Modified response + * Sets the response content-length * + * @param int $contentLength * @return ResponseInterface */ - public function setNotModified(); + public function setContentLength(int $contentLength): ResponseInterface; /** * Sets the response content-type mime, optionally the charset @@ -72,93 +94,93 @@ public function setNotModified(); * @param string $charset * @return ResponseInterface */ - public function setContentType($contentType, $charset = null); + public function setContentType(string $contentType, $charset = null): ResponseInterface; /** - * Sets the response content-length + * Sets output expire time header * - * @param int $contentLength + * @param \DateTime $datetime * @return ResponseInterface */ - public function setContentLength($contentLength); + public function setExpires(\DateTime $datetime): ResponseInterface; /** - * Redirect by HTTP to another action or URL + * Sets an attached file to be sent at the end of the request * - * @param mixed $location - * @param bool $externalRedirect - * @param int $statusCode + * @param string $filePath + * @param mixed $attachmentName * @return ResponseInterface */ - public function redirect($location = null, $externalRedirect = false, $statusCode = 302); + public function setFileToSend(string $filePath, $attachmentName = null): ResponseInterface; /** - * Sets HTTP response body + * Overwrites a header in the response * - * @param string $content + * @param string $name + * @param mixed $value * @return ResponseInterface */ - public function setContent($content); + public function setHeader(string $name, $value): ResponseInterface; /** * Sets HTTP response body. The parameter is automatically converted to JSON * - * + * ```php * $response->setJsonContent( * [ * "status" => "OK", * ] * ); - * + * ``` * * @param mixed $content * @return ResponseInterface */ - public function setJsonContent($content); + public function setJsonContent($content): ResponseInterface; /** - * Appends a string to the HTTP response body + * Sends a Not-Modified response * - * @param mixed $content * @return ResponseInterface */ - public function appendContent($content); + public function setNotModified(): ResponseInterface; /** - * Gets the HTTP response body + * Send a raw header to the response * - * @return string + * @param string $header + * @return ResponseInterface */ - public function getContent(); + public function setRawHeader(string $header): ResponseInterface; /** - * Sends headers to the client + * Sets the HTTP response code * + * @param int $code + * @param string $message * @return ResponseInterface */ - public function sendHeaders(); + public function setStatusCode(int $code, string $message = null): ResponseInterface; /** - * Sends cookies to the client + * Prints out HTTP response to the client * * @return ResponseInterface */ - public function sendCookies(); + public function send(): ResponseInterface; /** - * Prints out HTTP response to the client + * Sends cookies to the client * * @return ResponseInterface */ - public function send(); + public function sendCookies(): ResponseInterface; /** - * Sets an attached file to be sent at the end of the request + * Sends headers to the client * - * @param string $filePath - * @param mixed $attachmentName - * @return ResponseInterface + * @return bool|ResponseInterface */ - public function setFileToSend($filePath, $attachmentName = null); + public function sendHeaders(); } diff --git a/src/Phalcon/http/message/AbstractCommon.php b/src/Phalcon/http/message/AbstractCommon.php new file mode 100644 index 00000000..99f4f9c7 --- /dev/null +++ b/src/Phalcon/http/message/AbstractCommon.php @@ -0,0 +1,41 @@ + + */ + protected $body; + + /** + * @var + */ + protected $headers; + + /** + * Retrieves the HTTP protocol version as a string. + * + * The string MUST contain only the HTTP version number (e.g., '1.1', + * '1.0'). + * + * @return string HTTP protocol version. + * + * @var string + */ + protected $protocolVersion = '1.1'; + + /** + * Retrieves the URI instance. + * + * This method MUST return a UriInterface instance. + * + * @see http://tools.ietf.org/html/rfc3986#section-4.3 + * + * @var UriInterface + */ + protected $uri; + + + /** + * Gets the body of the message. + * + * @return + */ + public function getBody() {} + + /** + * Retrieves the HTTP protocol version as a string. + * + * The string MUST contain only the HTTP version number (e.g., '1.1', + * '1.0'). + * + * @return string + */ + public function getProtocolVersion(): string {} + + /** + * Retrieves the URI instance. + * + * This method MUST return a UriInterface instance. + * + * @return UriInterface + */ + public function getUri() {} + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name + * + * @param mixed $name + * @return array + */ + public function getHeader($name): array {} + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name + * + * @param mixed $name + * @return string + */ + public function getHeaderLine($name): string {} + + /** + * Retrieves all message header values. + * + * The keys represent the header name as it will be sent over the wire, and + * each value is an array of strings associated with the header. + * + * // Represent the headers as a string + * foreach ($message->getHeaders() as $name => $values) { + * echo $name . ': ' . implode(', ', $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return array + */ + public function getHeaders(): array {} + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name + * + * @param mixed $name + * @return bool + */ + public function hasHeader($name): bool {} + + /** + * Return an instance with the specified header appended with the given + * value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string|string[] $value + * + * @param string $name + * @param mixed $value + * @return object + */ + public function withAddedHeader($name, $value) {} + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body + * + * @throws InvalidArgumentException When the body is not valid. + * + * @param \Psr\Http\Message\StreamInterface $body + * @return object + */ + public function withBody(\Psr\Http\Message\StreamInterface $body) {} + + /** + * Return an instance with the provided value replacing the specified + * header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string|string[] $value + * + * @throws InvalidArgumentException for invalid header names or values. + * + * @param string $name + * @param mixed $value + * @return object + */ + public function withHeader($name, $value) {} + + /** + * Return an instance with the specified HTTP protocol version. + * + * The version string MUST contain only the HTTP version number (e.g., + * '1.1', '1.0'). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new protocol version. + * + * @param string $version + * + * @param mixed $version + * @return object + */ + public function withProtocolVersion($version) {} + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name + * + * @param mixed $name + * @return object + */ + public function withoutHeader($name) {} + + /** + * Ensure Host is the first header. + * + * @see: http://tools.ietf.org/html/rfc7230#section-5.4 + * + * @param Collection $collection + * + * @param \Phalcon\Collection $collection + * @return \Phalcon\Collection + */ + final protected function checkHeaderHost(\Phalcon\Collection $collection): Collection {} + + /** + * Check the name of the header. Throw exception if not valid + * + * @see http://tools.ietf.org/html/rfc7230#section-3.2 + * + * @param mixed $name + * @param $name + */ + final protected function checkHeaderName($name) {} + + /** + * Validates a header value + * + * Most HTTP header field values are defined using common syntax + * components (token, quoted-string, and comment) separated by + * whitespace or specific delimiting characters. Delimiters are chosen + * from the set of US-ASCII visual characters not allowed in a token + * (DQUOTE and '(),/:;<=>?@[\]{}'). + * + * token = 1tchar + * + * tchar = '!' / '#' / '$' / '%' / '&' / ''' / '' + * / '+' / '-' / '.' / '^' / '_' / '`' / '|' / '~' + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * + * A string of text is parsed as a single value if it is quoted using + * double-quote marks. + * + * quoted-string = DQUOTE( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * + * Comments can be included in some HTTP header fields by surrounding + * the comment text with parentheses. Comments are only allowed in + * fields containing 'comment' as part of their field value definition. + * + * comment = '('( ctext / quoted-pair / comment ) ')' + * ctext = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text + * + * The backslash octet ('\') can be used as a single-octet quoting + * mechanism within quoted-string and comment constructs. Recipients + * that process the value of a quoted-string MUST handle a quoted-pair + * as if it were replaced by the octet following the backslash. + * + * quoted-pair = '\' ( HTAB / SP / VCHAR / obs-text ) + * + * A sender SHOULD NOT generate a quoted-pair in a quoted-string except + * where necessary to quote DQUOTE and backslash octets occurring within + * that string. A sender SHOULD NOT generate a quoted-pair in a comment + * except where necessary to quote parentheses ['(' and ')'] and + * backslash octets occurring within that comment. + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * + * @param mixed $value + * @param $value + */ + final protected function checkHeaderValue($value) {} + + /** + * Returns the header values checked for validity + * + * @param $values + * + * @param mixed $values + * @return array + */ + final protected function getHeaderValue($values): array {} + + /** + * Return the host and if applicable the port + * + * @param UriInterface $uri + * + * @param \Psr\Http\Message\UriInterface $uri + * @return string + */ + final protected function getUriHost(\Psr\Http\Message\UriInterface $uri): string {} + + /** + * Populates the header collection + * + * @param array $headers + * + * @param array $headers + * @return \Phalcon\Collection + */ + final protected function populateHeaderCollection(array $headers): Collection {} + + /** + * Set a valid stream + * + * @param string $mode + * + * @param StreamInterface|resource|string $body + * @param string $mode + * @return \Psr\Http\Message\StreamInterface + */ + final protected function processBody($body = 'php://memory', string $mode = 'r+b'): StreamInterface {} + + /** + * Sets the headers + * + * @param $headers + * + * @param mixed $headers + * @return \Phalcon\Collection + */ + final protected function processHeaders($headers): Collection {} + + /** + * Checks the protocol + * + * @param string $protocol + * + * @param mixed $protocol + * @return string + */ + final protected function processProtocol($protocol = ''): string {} + +} diff --git a/src/Phalcon/http/message/AbstractRequest.php b/src/Phalcon/http/message/AbstractRequest.php new file mode 100644 index 00000000..3fdf32fd --- /dev/null +++ b/src/Phalcon/http/message/AbstractRequest.php @@ -0,0 +1,165 @@ +getQuery()` or from the `QUERY_STRING` server param. + * + * @var array + */ + private $queryParams = array(); + + /** + * Retrieve server parameters. + * + * Retrieves data related to the incoming request environment, + * typically derived from PHP's $_SERVER superglobal. The data IS NOT + * REQUIRED to originate from $_SERVER. + * + * @var array + */ + private $serverParams = array(); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @var array + */ + private $uploadedFiles = array(); + + + /** + * Retrieve cookies. + * + * Retrieves cookies sent by the client to the server. + * + * The data MUST be compatible with the structure of the $_COOKIE + * superglobal. + * + * @return array + */ + public function getCookieParams(): array {} + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return mixed + */ + public function getParsedBody() {} + + /** + * Retrieve query string arguments. + * + * Retrieves the deserialized query string arguments, if any. + * + * Note: the query params might not be in sync with the URI or server + * params. If you need to ensure you are only getting the original + * values, you may need to parse the query string from + * `getUri()->getQuery()` or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(): array {} + + /** + * Retrieve server parameters. + * + * Retrieves data related to the incoming request environment, + * typically derived from PHP's $_SERVER superglobal. The data IS NOT + * REQUIRED to originate from $_SERVER. + * + * @return array + */ + public function getServerParams(): array {} + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array + */ + public function getUploadedFiles(): array {} + + /** + * ServerRequest constructor. + * + * @param string $method + * @param UriInterface|string|null $uri + * @param array $serverParams + * @param StreamInterface|string $body + * @param array $headers + * @param array $cookies + * @param array $queryParams + * @param array $uploadFiles + * @param null|array|object $parsedBody + * @param string $protocol + */ + public function __construct(string $method = 'GET', $uri = null, array $serverParams = array(), $body = 'php://input', $headers = array(), array $cookies = array(), array $queryParams = array(), array $uploadFiles = array(), $parsedBody = null, string $protocol = '1.1') {} + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @param mixed|null $defaultValue + * + * @param string $name + * @param mixed $defaultValue + * @return mixed + */ + public function getAttribute($name, $defaultValue = null) {} + + /** + * Retrieve attributes derived from the request. + * + * The request 'attributes' may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array + */ + public function getAttributes(): array {} + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @param mixed $value + * + * @param string $name + * @param mixed $value + * @return ServerRequest + */ + public function withAttribute($name, $value): ServerRequest {} + + /** + * Return an instance with the specified cookies. + * + * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST + * be compatible with the structure of $_COOKIE. Typically, this data will + * be injected at instantiation. + * + * This method MUST NOT update the related Cookie header of the request + * instance, nor related values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated cookie values. + * + * @param array $cookies + * + * @param array $cookies + * @return ServerRequest + */ + public function withCookieParams(array $cookies): ServerRequest {} + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or + * objects, or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array|object|null $data + * + * @throws InvalidArgumentException if an unsupported argument type is + * provided. + * + * @param mixed $data + * @return ServerRequest + */ + public function withParsedBody($data): ServerRequest {} + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query + * + * @param array $query + * @return ServerRequest + */ + public function withQueryParams(array $query): ServerRequest {} + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles + * + * @throws InvalidArgumentException if an invalid structure is provided. + * + * @param array $uploadedFiles + * @return ServerRequest + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequest {} + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @param string $name + * + * @param mixed $name + * @return ServerRequest + */ + public function withoutAttribute($name): ServerRequest {} + + /** + * Checks the uploaded files + * + * @param array $files + */ + private function checkUploadedFiles(array $files) {} + +} diff --git a/src/Phalcon/http/message/ServerRequestFactory.php b/src/Phalcon/http/message/ServerRequestFactory.php new file mode 100644 index 00000000..2821ea96 --- /dev/null +++ b/src/Phalcon/http/message/ServerRequestFactory.php @@ -0,0 +1,209 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class InvalidArgumentException extends InvalidArgumentException implements \Throwable +{ + +} diff --git a/src/Phalcon/http/message/stream/Input.php b/src/Phalcon/http/message/stream/Input.php new file mode 100644 index 00000000..40b7b316 --- /dev/null +++ b/src/Phalcon/http/message/stream/Input.php @@ -0,0 +1,76 @@ + + * ```php * use Phalcon\Mvc\Controller; * * class PostsController extends Controller @@ -20,58 +20,58 @@ * foreach ($this->request->getUploadedFiles() as $file) { * echo $file->getName(), " ", $file->getSize(), "\n"; * } - * } + * } * } * } - * + * ``` */ class File implements \Phalcon\Http\Request\FileInterface { + /** + * @var string|null + */ + protected $error; - protected $_name; + /** + * @var string + */ + protected $extension; + /** + * @var string|null + */ + protected $key; - protected $_tmp; + protected $name; - protected $_size; + protected $realType; - protected $_type; + protected $size; - protected $_realType; - /** - * @var string|null - */ - protected $_error; + protected $tmp; - /** - * @var string|null - */ - protected $_key; - /** - * @var string - */ - protected $_extension; + protected $type; /** * @return string|null */ - public function getError() {} + public function getError(): ?string {} /** - * @return string|null + * @return string */ - public function getKey() {} + public function getExtension(): string {} /** - * @return string + * @return string|null */ - public function getExtension() {} + public function getKey(): ?string {} /** * Phalcon\Http\Request\File constructor @@ -82,47 +82,47 @@ public function getExtension() {} public function __construct(array $file, $key = null) {} /** - * Returns the file size of the uploaded file + * Returns the real name of the uploaded file * - * @return int + * @return string */ - public function getSize() {} + public function getName(): string {} /** - * Returns the real name of the uploaded file + * Gets the real mime type of the upload file using finfo * * @return string */ - public function getName() {} + public function getRealType(): string {} /** - * Returns the temporary name of the uploaded file + * Returns the file size of the uploaded file * - * @return string + * @return int */ - public function getTempName() {} + public function getSize(): int {} /** - * Returns the mime type reported by the browser - * This mime type is not completely secure, use getRealType() instead + * Returns the temporary name of the uploaded file * * @return string */ - public function getType() {} + public function getTempName(): string {} /** - * Gets the real mime type of the upload file using finfo + * Returns the mime type reported by the browser + * This mime type is not completely secure, use getRealType() instead * * @return string */ - public function getRealType() {} + public function getType(): string {} /** * Checks whether the file has been uploaded via Post. * * @return bool */ - public function isUploadedFile() {} + public function isUploadedFile(): bool {} /** * Moves the temporary file to a destination within the application @@ -130,6 +130,6 @@ public function isUploadedFile() {} * @param string $destination * @return bool */ - public function moveTo($destination) {} + public function moveTo(string $destination): bool {} } diff --git a/src/Phalcon/http/request/FileInterface.php b/src/Phalcon/http/request/FileInterface.php index 913d759b..69f37a10 100644 --- a/src/Phalcon/http/request/FileInterface.php +++ b/src/Phalcon/http/request/FileInterface.php @@ -11,40 +11,40 @@ interface FileInterface { /** - * Returns the file size of the uploaded file + * Returns the real name of the uploaded file * - * @return int + * @return string */ - public function getSize(); + public function getName(): string; /** - * Returns the real name of the uploaded file + * Gets the real mime type of the upload file using finfo * * @return string */ - public function getName(); + public function getRealType(): string; /** - * Returns the temporal name of the uploaded file + * Returns the file size of the uploaded file * - * @return string + * @return int */ - public function getTempName(); + public function getSize(): int; /** - * Returns the mime type reported by the browser - * This mime type is not completely secure, use getRealType() instead + * Returns the temporal name of the uploaded file * * @return string */ - public function getType(); + public function getTempName(): string; /** - * Gets the real mime type of the upload file using finfo + * Returns the mime type reported by the browser + * This mime type is not completely secure, use getRealType() instead * * @return string */ - public function getRealType(); + public function getType(): string; /** * Move the temporary file to a destination @@ -52,6 +52,6 @@ public function getRealType(); * @param string $destination * @return bool */ - public function moveTo($destination); + public function moveTo(string $destination): bool; } diff --git a/src/Phalcon/http/response/Cookies.php b/src/Phalcon/http/response/Cookies.php index 8f7c5f7a..8e63b483 100644 --- a/src/Phalcon/http/response/Cookies.php +++ b/src/Phalcon/http/response/Cookies.php @@ -7,12 +7,13 @@ * * This class is a bag to manage the cookies. * - * A cookies bag is automatically registered as part of the 'response' service in the DI. - * By default, cookies are automatically encrypted before being sent to the client and are - * decrypted when retrieved from the user. To set sign key used to generate a message - * authentication code use `Phalcon\Http\Response\Cookies::setSignKey`. + * A cookies bag is automatically registered as part of the 'response' service + * in the DI. By default, cookies are automatically encrypted before being sent + * to the client and are decrypted when retrieved from the user. To set sign key + * used to generate a message authentication code use + * `Phalcon\Http\Response\Cookies::setSignKey()`. * - * + * ```php * use Phalcon\Di; * use Phalcon\Crypt; * use Phalcon\Http\Response\Cookies; @@ -26,6 +27,7 @@ * * // The `$key' should have been previously generated in a cryptographically safe way. * $key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"; + * * $crypt->setKey($key); * * return $crypt; @@ -40,26 +42,24 @@ * // The `$key' MUST be at least 32 characters long and generated using a * // cryptographically secure pseudo random generator. * $key = "#1dj8$=dp?.ak//j1V$~%0XaK\xb1\x8d\xa9\x98\x054t7w!z%CF-Jk\x98\x05\\\x5c"; + * * $cookies->setSignKey($key); * * return $cookies; * } * ); - * + * ``` */ class Cookies implements \Phalcon\Http\Response\CookiesInterface, \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; - + protected $container; - protected $_registered = false; + protected $cookies = array(); - protected $_useEncryption = true; - - protected $_cookies; + protected $registered = false; /** * The cookie's sign key. @@ -69,63 +69,85 @@ class Cookies implements \Phalcon\Http\Response\CookiesInterface, \Phalcon\Di\In protected $signKey = null; + protected $useEncryption = true; + + /** * Phalcon\Http\Response\Cookies constructor * * @param bool $useEncryption * @param string $signKey */ - public function __construct($useEncryption = true, $signKey = null) {} + public function __construct(bool $useEncryption = true, string $signKey = null) {} /** - * Sets the cookie's sign key. - * - * The `$signKey' MUST be at least 32 characters long - * and generated using a cryptographically secure pseudo random generator. + * Deletes a cookie by its name + * This method does not removes cookies from the _COOKIE superglobal * - * Use NULL to disable cookie signing. + * @param string $name + * @return bool + */ + public function delete(string $name): bool {} + + /** + * Gets a cookie from the bag * - * @see \Phalcon\Security\Random - * @param string $signKey + * @param string $name * @return \Phalcon\Http\CookieInterface */ - public function setSignKey($signKey = null) {} + public function get(string $name): CookieInterface {} /** - * Sets the dependency injector + * Gets all cookies from the bag * - * @param \Phalcon\DiInterface $dependencyInjector + * @return array */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function getCookies(): array {} /** * Returns the internal dependency injector * - * @return \Phalcon\DiInterface + * @return \Phalcon\Di\DiInterface */ - public function getDI() {} + public function getDI(): DiInterface {} /** - * Set if cookies in the bag must be automatically encrypted/decrypted + * Check if a cookie is defined in the bag or exists in the _COOKIE + * superglobal * - * @param bool $useEncryption - * @return \Phalcon\Http\Response\CookiesInterface + * @param string $name + * @return bool */ - public function useEncryption($useEncryption) {} + public function has(string $name): bool {} /** * Returns if the bag is automatically encrypting/decrypting cookies * * @return bool */ - public function isUsingEncryption() {} + public function isUsingEncryption(): bool {} + + /** + * Reset set cookies + * + * @return \Phalcon\Http\Response\CookiesInterface + */ + public function reset(): CookiesInterface {} + + /** + * Sends the cookies to the client + * Cookies aren't sent if headers are sent in the current request + * + * @return bool + */ + public function send(): bool {} /** * Sets a cookie to be sent at the end of the request. * * This method overrides any cookie set before with the same name. * - * + * ```php * use Phalcon\Http\Response\Cookies; * * $now = new DateTimeImmutable(); @@ -137,7 +159,7 @@ public function isUsingEncryption() {} * json_encode(['user_id' => 1]), * (int) $tomorrow->format('U'), * ); - * + * ``` * * @param string $name * @param mixed $value @@ -148,46 +170,35 @@ public function isUsingEncryption() {} * @param bool $httpOnly * @return \Phalcon\Http\Response\CookiesInterface */ - public function set($name, $value = null, $expire = 0, $path = '/', $secure = null, $domain = null, $httpOnly = null) {} + public function set(string $name, $value = null, int $expire = 0, string $path = '/', bool $secure = null, string $domain = null, bool $httpOnly = null): CookiesInterface {} /** - * Gets a cookie from the bag + * Sets the dependency injector * - * @param string $name - * @return \Phalcon\Http\Response\CookiesInterface + * @param \Phalcon\Di\DiInterface $container */ - public function get($name) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Check if a cookie is defined in the bag or exists in the _COOKIE superglobal + * Sets the cookie's sign key. * - * @param string $name - * @return bool - */ - public function has($name) {} - - /** - * Deletes a cookie by its name - * This method does not removes cookies from the _COOKIE superglobal + * The `$signKey' MUST be at least 32 characters long + * and generated using a cryptographically secure pseudo random generator. * - * @param string $name - * @return bool - */ - public function delete($name) {} - - /** - * Sends the cookies to the client - * Cookies aren't sent if headers are sent in the current request + * Use NULL to disable cookie signing. * - * @return bool + * @see \Phalcon\Security\Random + * @param string $signKey + * @return \Phalcon\Http\CookieInterface */ - public function send() {} + public function setSignKey(string $signKey = null): CookieInterface {} /** - * Reset set cookies + * Set if cookies in the bag must be automatically encrypted/decrypted * + * @param bool $useEncryption * @return \Phalcon\Http\Response\CookiesInterface */ - public function reset() {} + public function useEncryption(bool $useEncryption): CookiesInterface {} } diff --git a/src/Phalcon/http/response/CookiesInterface.php b/src/Phalcon/http/response/CookiesInterface.php index cd1c100e..abe18b6f 100644 --- a/src/Phalcon/http/response/CookiesInterface.php +++ b/src/Phalcon/http/response/CookiesInterface.php @@ -11,71 +11,71 @@ interface CookiesInterface { /** - * Set if cookies in the bag must be automatically encrypted/decrypted - * - * @param bool $useEncryption - * @return CookiesInterface - */ - public function useEncryption($useEncryption); - - /** - * Returns if the bag is automatically encrypting/decrypting cookies + * Deletes a cookie by its name + * This method does not removes cookies from the _COOKIE superglobal * + * @param string $name * @return bool */ - public function isUsingEncryption(); + public function delete(string $name): bool; /** - * Sets a cookie to be sent at the end of the request + * Gets a cookie from the bag * * @param string $name - * @param mixed $value - * @param int $expire - * @param string $path - * @param bool $secure - * @param string $domain - * @param bool $httpOnly - * @return CookiesInterface + * @return \Phalcon\Http\CookieInterface */ - public function set($name, $value = null, $expire = 0, $path = '/', $secure = null, $domain = null, $httpOnly = null); + public function get(string $name): CookieInterface; /** - * Gets a cookie from the bag + * Check if a cookie is defined in the bag or exists in the _COOKIE superglobal * * @param string $name - * @return CookiesInterface + * @return bool */ - public function get($name); + public function has(string $name): bool; /** - * Check if a cookie is defined in the bag or exists in the _COOKIE superglobal + * Returns if the bag is automatically encrypting/decrypting cookies * - * @param string $name * @return bool */ - public function has($name); + public function isUsingEncryption(): bool; /** - * Deletes a cookie by its name - * This method does not removes cookies from the _COOKIE superglobal + * Reset set cookies * - * @param string $name - * @return bool + * @return CookiesInterface */ - public function delete($name); + public function reset(): CookiesInterface; /** * Sends the cookies to the client * * @return bool */ - public function send(); + public function send(): bool; /** - * Reset set cookies + * Sets a cookie to be sent at the end of the request + * + * @param string $name + * @param mixed $value + * @param int $expire + * @param string $path + * @param bool $secure + * @param string $domain + * @param bool $httpOnly + * @return CookiesInterface + */ + public function set(string $name, $value = null, int $expire = 0, string $path = '/', bool $secure = null, string $domain = null, bool $httpOnly = null): CookiesInterface; + + /** + * Set if cookies in the bag must be automatically encrypted/decrypted * + * @param bool $useEncryption * @return CookiesInterface */ - public function reset(); + public function useEncryption(bool $useEncryption): CookiesInterface; } diff --git a/src/Phalcon/http/response/Headers.php b/src/Phalcon/http/response/Headers.php index 7ccc1a96..31f52cbd 100644 --- a/src/Phalcon/http/response/Headers.php +++ b/src/Phalcon/http/response/Headers.php @@ -10,64 +10,64 @@ class Headers implements \Phalcon\Http\Response\HeadersInterface { - protected $_headers = array(); + protected $headers = array(); /** - * Sets a header to be sent at the end of the request + * Gets a header value from the internal bag * * @param string $name - * @param string $value + * @return string|bool */ - public function set($name, $value) {} + public function get(string $name) {} /** - * Gets a header value from the internal bag + * Sets a header to be sent at the end of the request * * @param string $name - * @return string|bool + * @return bool */ - public function get($name) {} + public function has(string $name): bool {} /** - * Sets a raw header to be sent at the end of the request + * Removes a header to be sent at the end of the request * * @param string $header */ - public function setRaw($header) {} + public function remove(string $header) {} /** - * Removes a header to be sent at the end of the request - * - * @param string $header + * Reset set headers */ - public function remove($header) {} + public function reset() {} /** * Sends the headers to the client * * @return bool */ - public function send() {} + public function send(): bool {} /** - * Reset set headers + * Sets a header to be sent at the end of the request + * + * @param string $name + * @param string $value */ - public function reset() {} + public function set(string $name, string $value) {} /** - * Returns the current headers as an array + * Sets a raw header to be sent at the end of the request * - * @return array + * @param string $header */ - public function toArray() {} + public function setRaw(string $header) {} /** - * Restore a \Phalcon\Http\Response\Headers object + * Returns the current headers as an array * - * @param array $data - * @return \Phalcon\Http\Response\HeadersInterface + * @return array */ - public static function __set_state(array $data) {} + public function toArray(): array {} } diff --git a/src/Phalcon/http/response/HeadersInterface.php b/src/Phalcon/http/response/HeadersInterface.php index 9d7349ea..a2b439a8 100644 --- a/src/Phalcon/http/response/HeadersInterface.php +++ b/src/Phalcon/http/response/HeadersInterface.php @@ -11,46 +11,46 @@ interface HeadersInterface { /** - * Sets a header to be sent at the end of the request + * Gets a header value from the internal bag * * @param string $name - * @param string $value + * @return string|bool */ - public function set($name, $value); + public function get(string $name); /** - * Gets a header value from the internal bag + * Returns true if the header is set, false otherwise * * @param string $name - * @return string|bool + * @return bool */ - public function get($name); + public function has(string $name): bool; /** - * Sets a raw header to be sent at the end of the request - * - * @param string $header + * Reset set headers */ - public function setRaw($header); + public function reset(); /** * Sends the headers to the client * * @return bool */ - public function send(); + public function send(): bool; /** - * Reset set headers + * Sets a header to be sent at the end of the request + * + * @param string $name + * @param string $value */ - public function reset(); + public function set(string $name, string $value); /** - * Restore a \Phalcon\Http\Response\Headers object + * Sets a raw header to be sent at the end of the request * - * @param array $data - * @return HeadersInterface + * @param string $header */ - public static function __set_state(array $data); + public function setRaw(string $header); } diff --git a/src/Phalcon/http/server/AbstractMiddleware.php b/src/Phalcon/http/server/AbstractMiddleware.php new file mode 100644 index 00000000..8f3353b7 --- /dev/null +++ b/src/Phalcon/http/server/AbstractMiddleware.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Enum +{ + + const AUTO = 4; + + + const HEIGHT = 3; + + + const INVERSE = 5; + + + const NONE = 1; + + + const PRECISE = 6; + + + const TENSILE = 7; + + + const WIDTH = 2; + + + const HORIZONTAL = 11; + + + const VERTICAL = 12; + + +} diff --git a/src/Phalcon/image/Exception.php b/src/Phalcon/image/Exception.php index 7e881cbe..d590f857 100644 --- a/src/Phalcon/image/Exception.php +++ b/src/Phalcon/image/Exception.php @@ -2,7 +2,14 @@ namespace Phalcon\Image; - +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ class Exception extends \Phalcon\Exception { diff --git a/src/Phalcon/image/Factory.php b/src/Phalcon/image/Factory.php deleted file mode 100644 index 36ef8eb9..00000000 --- a/src/Phalcon/image/Factory.php +++ /dev/null @@ -1,35 +0,0 @@ - - * use Phalcon\Image\Factory; - * - * $options = [ - * "width" => 200, - * "height" => 200, - * "file" => "upload/test.jpg", - * "adapter" => "imagick", - * ]; - * $image = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - - /** - * @param string $namespace - * @param mixed $config - */ - protected static function loadClass($namespace, $config) {} - -} diff --git a/src/Phalcon/image/ImageFactory.php b/src/Phalcon/image/ImageFactory.php new file mode 100644 index 00000000..234d2713 --- /dev/null +++ b/src/Phalcon/image/ImageFactory.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +interface AdapterInterface +{ + + /** + * @param string $color + * @param int $opacity + */ + public function background(string $color, int $opacity = 100); + + /** + * @param int $radius + */ + public function blur(int $radius); + + /** + * @param int $width + * @param int $height + * @param int $offsetX + * @param int $offsetY + */ + public function crop(int $width, int $height, int $offsetX = null, int $offsetY = null); + + /** + * @param int $direction + */ + public function flip(int $direction); + + /** + * @param AdapterInterface $watermark + */ + public function mask(AdapterInterface $watermark); + + /** + * @param int $amount + */ + public function pixelate(int $amount); + + /** + * @param int $height + * @param int $opacity + * @param bool $fadeIn + */ + public function reflection(int $height, int $opacity = 100, bool $fadeIn = false); + + /** + * @param string $ext + * @param int $quality + */ + public function render(string $ext = null, int $quality = 100); + + /** + * @param int $width + * @param int $height + * @param int $master + */ + public function resize(int $width = null, int $height = null, int $master = Image::AUTO); + + /** + * @param int $degrees + */ + public function rotate(int $degrees); + + /** + * @param string $file + * @param int $quality + */ + public function save(string $file = null, int $quality = 100); + + /** + * @param int $amount + */ + public function sharpen(int $amount); + + /** + * @param string $text + * @param int $offsetX + * @param int $offsetY + * @param int $opacity + * @param string $color + * @param int $size + * @param string $fontfile + */ + public function text(string $text, int $offsetX = 0, int $offsetY = 0, int $opacity = 100, string $color = '000000', int $size = 12, string $fontfile = null); + + /** + * @param AdapterInterface $watermark + * @param int $offsetX + * @param int $offsetY + * @param int $opacity + */ + public function watermark(AdapterInterface $watermark, int $offsetX = 0, int $offsetY = 0, int $opacity = 100); + +} diff --git a/src/Phalcon/image/adapter/Gd.php b/src/Phalcon/image/adapter/Gd.php index c162e8a3..e8769205 100644 --- a/src/Phalcon/image/adapter/Gd.php +++ b/src/Phalcon/image/adapter/Gd.php @@ -2,30 +2,58 @@ namespace Phalcon\Image\Adapter; - -class Gd extends \Phalcon\Image\Adapter +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Gd extends \Phalcon\Image\Adapter\AbstractAdapter { - static protected $_checked = false; + static protected $checked = false; + + + /** + * @param string $file + * @param int $width + * @param int $height + */ + public function __construct(string $file, int $width = null, int $height = null) {} + + public function __destruct() {} /** * @return bool */ - public static function check() {} + public static function check(): bool {} /** - * @param string $file - * @param int $width - * @param int $height + * @return string + */ + public static function getVersion(): string {} + + /** + * @param int $r + * @param int $g + * @param int $b + * @param int $opacity */ - public function __construct($file, $width = null, $height = null) {} + protected function processBackground(int $r, int $g, int $b, int $opacity) {} + + /** + * @param int $radius + */ + protected function processBlur(int $radius) {} /** * @param int $width * @param int $height */ - protected function _resize($width, $height) {} + protected function processCreate(int $width, int $height) {} /** * @param int $width @@ -33,93 +61,77 @@ protected function _resize($width, $height) {} * @param int $offsetX * @param int $offsetY */ - protected function _crop($width, $height, $offsetX, $offsetY) {} + protected function processCrop(int $width, int $height, int $offsetX, int $offsetY) {} /** - * @param int $degrees + * @param int $direction */ - protected function _rotate($degrees) {} + protected function processFlip(int $direction) {} /** - * @param int $direction + * @param AdapterInterface $mask */ - protected function _flip($direction) {} + protected function processMask(AdapterInterface $mask) {} /** * @param int $amount */ - protected function _sharpen($amount) {} + protected function processPixelate(int $amount) {} /** * @param int $height * @param int $opacity * @param bool $fadeIn */ - protected function _reflection($height, $opacity, $fadeIn) {} + protected function processReflection(int $height, int $opacity, bool $fadeIn) {} /** - * @param \Phalcon\Image\Adapter $watermark - * @param int $offsetX - * @param int $offsetY - * @param int $opacity - */ - protected function _watermark(\Phalcon\Image\Adapter $watermark, $offsetX, $offsetY, $opacity) {} - - /** - * @param string $text - * @param int $offsetX - * @param int $offsetY - * @param int $opacity - * @param int $r - * @param int $g - * @param int $b - * @param int $size - * @param string $fontfile + * @param string $ext + * @param int $quality */ - protected function _text($text, $offsetX, $offsetY, $opacity, $r, $g, $b, $size, $fontfile) {} + protected function processRender(string $ext, int $quality) {} /** - * @param \Phalcon\Image\Adapter $mask + * @param int $width + * @param int $height */ - protected function _mask(\Phalcon\Image\Adapter $mask) {} + protected function processResize(int $width, int $height) {} /** - * @param int $r - * @param int $g - * @param int $b - * @param int $opacity + * @param int $degrees */ - protected function _background($r, $g, $b, $opacity) {} + protected function processRotate(int $degrees) {} /** - * @param int $radius + * @param string $file + * @param int $quality */ - protected function _blur($radius) {} + protected function processSave(string $file, int $quality) {} /** * @param int $amount */ - protected function _pixelate($amount) {} - - /** - * @param string $file - * @param int $quality - */ - protected function _save($file, $quality) {} + protected function processSharpen(int $amount) {} /** - * @param string $ext - * @param int $quality + * @param string $text + * @param int $offsetX + * @param int $offsetY + * @param int $opacity + * @param int $r + * @param int $g + * @param int $b + * @param int $size + * @param string $fontfile */ - protected function _render($ext, $quality) {} + protected function processText(string $text, int $offsetX, int $offsetY, int $opacity, int $r, int $g, int $b, int $size, string $fontfile) {} /** - * @param int $width - * @param int $height + * @param AdapterInterface $watermark + * @param int $offsetX + * @param int $offsetY + * @param int $opacity */ - protected function _create($width, $height) {} - - - public function __destruct() {} + protected function processWatermark(AdapterInterface $watermark, int $offsetX, int $offsetY, int $opacity) {} } diff --git a/src/Phalcon/image/adapter/Imagick.php b/src/Phalcon/image/adapter/Imagick.php index 2164b7f7..6164a769 100644 --- a/src/Phalcon/image/adapter/Imagick.php +++ b/src/Phalcon/image/adapter/Imagick.php @@ -7,7 +7,7 @@ * * Image manipulation support. Allows images to be resized, cropped, etc. * - * + * ```php * $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); * * $image->resize(200, 200)->rotate(90)->crop(100, 100); @@ -15,24 +15,17 @@ * if ($image->save()) { * echo "success"; * } - * + * ``` */ -class Imagick extends \Phalcon\Image\Adapter +class Imagick extends \Phalcon\Image\Adapter\AbstractAdapter { - static protected $_version = 0; + static protected $checked = false; - static protected $_checked = false; + static protected $version = 0; - /** - * Checks if Imagick is enabled - * - * @return bool - */ - public static function check() {} - /** * \Phalcon\Image\Adapter\Imagick constructor * @@ -40,158 +33,166 @@ public static function check() {} * @param int $width * @param int $height */ - public function __construct($file, $width = null, $height = null) {} + public function __construct(string $file, int $width = null, int $height = null) {} /** - * Execute a resize. - * - * @param int $width - * @param int $height + * Destroys the loaded image to free up resources. */ - protected function _resize($width, $height) {} + public function __destruct() {} /** - * This method scales the images using liquid rescaling method. Only support Imagick + * Checks if Imagick is enabled * - * @param int $width new width - * @param int $height new height - * @param int $deltaX How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight. - * @param int $rigidity Introduces a bias for non-straight seams. This parameter is typically 0. + * @return bool */ - protected function _liquidRescale($width, $height, $deltaX, $rigidity) {} + public static function check(): bool {} /** - * Execute a crop. + * Get instance * - * @param int $width - * @param int $height - * @param int $offsetX - * @param int $offsetY + * @return \Imagick */ - protected function _crop($width, $height, $offsetX, $offsetY) {} + public function getInternalImInstance(): \Imagick {} /** - * Execute a rotation. + * Sets the limit for a particular resource in megabytes * - * @param int $degrees + * @link http://php.net/manual/ru/imagick.constants.php#imagick.constants.resourcetypes + * @param int $type + * @param int $limit */ - protected function _rotate($degrees) {} + public function setResourceLimit(int $type, int $limit) {} /** - * Execute a flip. + * Execute a background. * - * @param int $direction + * @param int $r + * @param int $g + * @param int $b + * @param int $opacity */ - protected function _flip($direction) {} + protected function processBackground(int $r, int $g, int $b, int $opacity) {} /** - * Execute a sharpen. + * Blur image * - * @param int $amount + * @param int $radius Blur radius */ - protected function _sharpen($amount) {} + protected function processBlur(int $radius) {} /** - * Execute a reflection. + * Execute a crop. * + * @param int $width * @param int $height - * @param int $opacity - * @param bool $fadeIn + * @param int $offsetX + * @param int $offsetY */ - protected function _reflection($height, $opacity, $fadeIn) {} + protected function processCrop(int $width, int $height, int $offsetX, int $offsetY) {} /** - * Execute a watermarking. + * Execute a flip. * - * @param \Phalcon\Image\Adapter $image - * @param int $offsetX - * @param int $offsetY - * @param int $opacity + * @param int $direction */ - protected function _watermark(\Phalcon\Image\Adapter $image, $offsetX, $offsetY, $opacity) {} + protected function processFlip(int $direction) {} /** - * Execute a text + * This method scales the images using liquid rescaling method. Only support + * Imagick * - * @param string $text - * @param mixed $offsetX - * @param mixed $offsetY - * @param int $opacity - * @param int $r - * @param int $g - * @param int $b - * @param int $size - * @param string $fontfile + * @param int $width new width + * @param int $height new height + * @param int $deltaX How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight. + * @param int $rigidity Introduces a bias for non-straight seams. This parameter is typically 0. */ - protected function _text($text, $offsetX, $offsetY, $opacity, $r, $g, $b, $size, $fontfile) {} + protected function processLiquidRescale(int $width, int $height, int $deltaX, int $rigidity) {} /** * Composite one image onto another * - * @param \Phalcon\Image\Adapter $image + * @param AdapterInterface $image */ - protected function _mask(\Phalcon\Image\Adapter $image) {} + protected function processMask(AdapterInterface $image) {} /** - * Execute a background. + * Pixelate image * - * @param int $r - * @param int $g - * @param int $b + * @param int $amount amount to pixelate + */ + protected function processPixelate(int $amount) {} + + /** + * Execute a reflection. + * + * @param int $height * @param int $opacity + * @param bool $fadeIn */ - protected function _background($r, $g, $b, $opacity) {} + protected function processReflection(int $height, int $opacity, bool $fadeIn) {} /** - * Blur image + * Execute a render. * - * @param int $radius Blur radius + * @param string $extension + * @param int $quality + * @return string */ - protected function _blur($radius) {} + protected function processRender(string $extension, int $quality): string {} /** - * Pixelate image + * Execute a resize. * - * @param int $amount amount to pixelate + * @param int $width + * @param int $height */ - protected function _pixelate($amount) {} + protected function processResize(int $width, int $height) {} /** - * Execute a save. + * Execute a rotation. * - * @param string $file - * @param int $quality + * @param int $degrees */ - protected function _save($file, $quality) {} + protected function processRotate(int $degrees) {} /** - * Execute a render. + * Execute a save. * - * @param string $extension + * @param string $file * @param int $quality - * @return string */ - protected function _render($extension, $quality) {} + protected function processSave(string $file, int $quality) {} /** - * Destroys the loaded image to free up resources. + * Execute a sharpen. + * + * @param int $amount */ - public function __destruct() {} + protected function processSharpen(int $amount) {} /** - * Get instance + * Execute a text * - * @return \Imagick + * @param string $text + * @param mixed $offsetX + * @param mixed $offsetY + * @param int $opacity + * @param int $r + * @param int $g + * @param int $b + * @param int $size + * @param string $fontfile */ - public function getInternalImInstance() {} + protected function processText(string $text, $offsetX, $offsetY, int $opacity, int $r, int $g, int $b, int $size, string $fontfile) {} /** - * Sets the limit for a particular resource in megabytes + * Execute a watermarking. * - * @link http://php.net/manual/ru/imagick.constants.php#imagick.constants.resourcetypes - * @param int $type - * @param int $limit + * @param AdapterInterface $image + * @param int $offsetX + * @param int $offsetY + * @param int $opacity */ - public function setResourceLimit($type, $limit) {} + protected function processWatermark(AdapterInterface $image, int $offsetX, int $offsetY, int $opacity) {} } diff --git a/src/Phalcon/logger/Adapter.php b/src/Phalcon/logger/Adapter.php deleted file mode 100644 index 6332108c..00000000 --- a/src/Phalcon/logger/Adapter.php +++ /dev/null @@ -1,174 +0,0 @@ - + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class AdapterFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * AdapterFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @param string $fileName + * @param array $options + * @return AdapterInterface + */ + public function newInstance(string $name, string $fileName, array $options = array()): AdapterInterface {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/logger/AdapterInterface.php b/src/Phalcon/logger/AdapterInterface.php deleted file mode 100644 index a6ed7ba9..00000000 --- a/src/Phalcon/logger/AdapterInterface.php +++ /dev/null @@ -1,144 +0,0 @@ - - * use Phalcon\Logger\Factory; - * - * $options = [ - * "name" => "log.txt", - * "adapter" => "file", - * ]; - * $logger = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - - /** - * @param string $namespace - * @param mixed $config - */ - protected static function loadClass($namespace, $config) {} - -} diff --git a/src/Phalcon/logger/Formatter.php b/src/Phalcon/logger/Formatter.php deleted file mode 100644 index 24868d1c..00000000 --- a/src/Phalcon/logger/Formatter.php +++ /dev/null @@ -1,30 +0,0 @@ - $adapter1, + * 'remote' => $adapter2, + * 'manager' => $adapter3, + * ] + * ); + * + * // Log to all adapters + * $logger->error('Something went wrong'); + * + * // Log to specific adapters + * $logger + * ->excludeAdapters(['manager']) + * ->info('This does not go to the "manager" logger); + * ``` + */ +class Logger implements \Psr\Log\LoggerInterface +{ + + const ALERT = 2; + + + const CRITICAL = 1; + + + const CUSTOM = 8; + + + const DEBUG = 7; + + + const EMERGENCY = 0; + + + const ERROR = 3; + + + const INFO = 6; + + + const NOTICE = 5; + + + const WARNING = 4; + + /** + * The adapter stack + * + * @var AdapterInterface[] + */ + protected $adapters = array(); + + /** + * @var string + */ + protected $name = ''; + + /** + * The excluded adapters for this log process + * + * @var AdapterInterface[] + */ + protected $excluded = array(); + + + /** + * Constructor. + * + * @param string $name The name of the logger + * @param array $adapters The collection of adapters to be used for logging (default []) + */ + public function __construct(string $name, array $adapters = array()) {} + + /** + * Add an adapter to the stack. For processing we use FIFO + * + * @param string $name The name of the adapter + * @param $adapter The adapter to add to the stack + * @return Logger + */ + public function addAdapter(string $name, \Phalcon\Logger\Adapter\AdapterInterface $adapter): Logger {} + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string $message + * @param array $context + */ + public function alert($message, array $context = array()) {} + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string $message + * @param array $context + */ + public function critical($message, array $context = array()) {} + + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + */ + public function debug($message, array $context = array()) {} + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + */ + public function error($message, array $context = array()) {} + + /** + * System is unusable. + * + * @param string $message + * @param array $context + */ + public function emergency($message, array $context = array()) {} + + /** + * Exclude certain adapters. + * + * @param array $adapters + * @return Logger + */ + public function excludeAdapters(array $adapters = array()): Logger {} + + /** + * Returns an adapter from the stack + * + * @param string name The name of the adapter + * + * @throws + * @param string $name + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function getAdapter(string $name): AdapterInterface {} + + /** + * Returns the adapter stack array + * + * @return array + */ + public function getAdapters(): array {} + + /** + * Returns the name of the logger + * + * @return string + */ + public function getName(): string {} + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string $message + * @param array $context + */ + public function info($message, array $context = array()) {} + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + */ + public function log($level, $message, array $context = array()) {} + + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + */ + public function notice($message, array $context = array()) {} + + /** + * Removes an adapter from the stack + * + * @param string name The name of the adapter + * + * @throws + * @param string $name + * @return Logger + */ + public function removeAdapter(string $name): Logger {} + + /** + * Sets the adapters stack overriding what is already there + * + * @param array $adapters An array of adapters + * @return Logger + */ + public function setAdapters(array $adapters): Logger {} + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string $message + * @param array $context + */ + public function warning($message, array $context = array()) {} + + /** + * Adds a message to each handler for processing + * + * @param string message + * + * @throws + * @param int $level + * @param string $message + * @param array $context + * @return bool + */ + protected function addMessage(int $level, string $message, array $context = array()): bool {} + + /** + * Returns an array of log levels with integer to string conversion + * + * @return array + */ + protected function getLevels(): array {} + + /** + * Converts the level from string/word to an integer + * + * @param string|int $level + * @return int + */ + private function getLevelNumber($level): int {} + +} diff --git a/src/Phalcon/logger/LoggerFactory.php b/src/Phalcon/logger/LoggerFactory.php new file mode 100644 index 00000000..a53c608b --- /dev/null +++ b/src/Phalcon/logger/LoggerFactory.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +abstract class AbstractAdapter implements \Phalcon\Logger\Adapter\AdapterInterface +{ + /** + * Name of the default formatter class + * + * @var string + */ + protected $defaultFormatter = 'Line'; + + /** + * Formatter + * + * @var + */ + protected $formatter; + + /** + * Tells if there is an active transaction or not + * + * @var bool + */ + protected $inTransaction = false; + + /** + * Array with messages queued in the transaction + * + * @var array + */ + protected $queue = array(); + + + /** + * Destructor cleanup + */ + public function __destruct() {} + + /** + * Adds a message to the queue + * + * @param \Phalcon\Logger\Item $item + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function add(\Phalcon\Logger\Item $item): AdapterInterface {} + + /** + * Starts a transaction + * + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function begin(): AdapterInterface {} + + /** + * Commits the internal transaction + * + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function commit(): AdapterInterface {} + + /** + * @return \Phalcon\Logger\Formatter\FormatterInterface + */ + public function getFormatter(): FormatterInterface {} + + /** + * Returns the whether the logger is currently in an active transaction or not + * + * @return bool + */ + public function inTransaction(): bool {} + + /** + * Processes the message in the adapter + * + * @param \Phalcon\Logger\Item $item + */ + abstract public function process(\Phalcon\Logger\Item $item); + + /** + * Rollbacks the internal transaction + * + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function rollback(): AdapterInterface {} + + /** + * Sets the message formatter + * + * @param \Phalcon\Logger\Formatter\FormatterInterface $formatter + * @return \Phalcon\Logger\Adapter\AdapterInterface + */ + public function setFormatter(\Phalcon\Logger\Formatter\FormatterInterface $formatter): AdapterInterface {} + +} diff --git a/src/Phalcon/logger/adapter/Abstractadapter.php b/src/Phalcon/logger/adapter/Abstractadapter.php deleted file mode 100644 index 6abb00ee..00000000 --- a/src/Phalcon/logger/adapter/Abstractadapter.php +++ /dev/null @@ -1,100 +0,0 @@ - - */ - protected $formatter; - - /** - * Tells if there is an active transaction or not - * - * @var bool - */ - protected $inTransaction = false; - - /** - * Array with messages queued in the transaction - * - * @var array - */ - protected $queue = []; - - /** - * Destructor cleanup - */ - public function __destruct() - { - } - - /** - * Adds a message to the queue - */ - public function add(Item $item) : void - { - } - - /** - * Starts a transaction - */ - public function begin() : AdapterInterface - { - } - - /** - * Commits the internal transaction - */ - public function commit() : AdapterInterface - { - } - - public function getFormatter() : FormatterInterface - { - } - - /** - * Returns the whether the logger is currently in an active transaction or not - */ - public function inTransaction() : bool - { - } - - /** - * Processes the message in the adapter - */ - public function process(Item $item) : void - { - } - - /** - * Rollbacks the internal transaction - */ - public function rollback() : AdapterInterface - { - } - - /** - * Sets the message formatter - */ - public function setFormatter(FormatterInterface $formatter) : AdapterInterface - { - } -} diff --git a/src/Phalcon/logger/adapter/AdapterInterface.php b/src/Phalcon/logger/adapter/AdapterInterface.php new file mode 100644 index 00000000..b9317e56 --- /dev/null +++ b/src/Phalcon/logger/adapter/AdapterInterface.php @@ -0,0 +1,70 @@ + - * $logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log"); - * - * $logger->log("This is a message"); - * $logger->log(\Phalcon\Logger::ERROR, "This is an error"); - * $logger->error("This is another error"); - * - * $logger->close(); - * - */ -class File extends \Phalcon\Logger\Adapter -{ - /** - * File handler resource - * - * @var resource - */ - protected $_fileHandler; - - /** - * File Path - */ - protected $_path; - - /** - * Path options - */ - protected $_options; - - - /** - * File Path - */ - public function getPath() {} - - /** - * Phalcon\Logger\Adapter\File constructor - * - * @param string $name - * @param array $options - */ - public function __construct($name, $options = null) {} - - /** - * Returns the internal formatter - * - * @return \Phalcon\Logger\FormatterInterface - */ - public function getFormatter() {} - - /** - * Writes the log to the file itself - * - * @param string $message - * @param int $type - * @param int $time - * @param array $context - */ - public function logInternal($message, $type, $time, array $context) {} - - /** - * Closes the logger - * - * @return bool - */ - public function close() {} - - /** - * Opens the internal file handler after unserialization - */ - public function __wakeup() {} - -} diff --git a/src/Phalcon/logger/adapter/Firephp.php b/src/Phalcon/logger/adapter/Firephp.php deleted file mode 100644 index c509e369..00000000 --- a/src/Phalcon/logger/adapter/Firephp.php +++ /dev/null @@ -1,55 +0,0 @@ - - * use Phalcon\Logger\Adapter\Firephp; - * use Phalcon\Logger; - * - * $logger = new Firephp(); - * - * $logger->log(Logger::ERROR, "This is an error"); - * $logger->error("This is another error"); - * - * - * @deprecated Will be removed in 4.0.0 - */ -class Firephp extends \Phalcon\Logger\Adapter -{ - - private $_initialized = false; - - - private $_index = 1; - - - /** - * Returns the internal formatter - * - * @return \Phalcon\Logger\FormatterInterface - */ - public function getFormatter() {} - - /** - * Writes the log to the stream itself - * - * @param string $message - * @param int $type - * @param int $time - * @param array $context - */ - public function logInternal($message, $type, $time, array $context) {} - - /** - * Closes the logger - * - * @return bool - */ - public function close() {} - -} diff --git a/src/Phalcon/logger/adapter/Noop.php b/src/Phalcon/logger/adapter/Noop.php index 76f9e1a9..9f2e6578 100644 --- a/src/Phalcon/logger/adapter/Noop.php +++ b/src/Phalcon/logger/adapter/Noop.php @@ -2,35 +2,35 @@ namespace Phalcon\Logger\Adapter; -use Phalcon\Logger\Item; - /** * Phalcon\Logger\Adapter\Noop * * Adapter to store logs in plain text files * - * + * ```php * $logger = new \Phalcon\Logger\Adapter\Noop(); * * $logger->log(\Phalcon\Logger::ERROR, "This is an error"); * $logger->error("This is another error"); * * $logger->close(); - * + * ``` */ -class Noop extends AbstractAdapter +class Noop extends \Phalcon\Logger\Adapter\AbstractAdapter { - /** - * Closes the stream - */ - public function close() : bool - { - } - /** - * Processes the message i.e. writes it to the file - */ - public function process(Item $item) : void - { - } + /** + * Closes the stream + * + * @return bool + */ + public function close(): bool {} + + /** + * Processes the message i.e. writes it to the file + * + * @param \Phalcon\Logger\Item $item + */ + public function process(\Phalcon\Logger\Item $item) {} + } diff --git a/src/Phalcon/logger/adapter/Stream.php b/src/Phalcon/logger/adapter/Stream.php index 33279124..94b479a3 100644 --- a/src/Phalcon/logger/adapter/Stream.php +++ b/src/Phalcon/logger/adapter/Stream.php @@ -5,59 +5,76 @@ /** * Phalcon\Logger\Adapter\Stream * - * Sends logs to a valid PHP stream + * Adapter to store logs in plain text files * - * - * use Phalcon\Logger; - * use Phalcon\Logger\Adapter\Stream; - * - * $logger = new Stream("php://stderr"); + * ```php + * $logger = new \Phalcon\Logger\Adapter\Stream("app/logs/test.log"); * * $logger->log("This is a message"); - * $logger->log(Logger::ERROR, "This is an error"); + * $logger->log(\Phalcon\Logger::ERROR, "This is an error"); * $logger->error("This is another error"); - * + * + * $logger->close(); + * ``` */ -class Stream extends \Phalcon\Logger\Adapter +class Stream extends \Phalcon\Logger\Adapter\AbstractAdapter { /** - * File handler resource + * Stream handler resource * - * @var resource + * @var resource|null */ - protected $_stream; + protected $handler = null; + /** + * The file open mode. Defaults to "ab" + * + * @var string + */ + protected $mode = 'ab'; /** - * Phalcon\Logger\Adapter\Stream constructor + * Stream name * - * @param string $name - * @param array $options + * @var string + */ + protected $name; + + /** + * Path options + * + * @var array */ - public function __construct($name, $options = null) {} + protected $options; + /** - * Returns the internal formatter + * Stream name * - * @return \Phalcon\Logger\FormatterInterface + * @return string */ - public function getFormatter() {} + public function getName(): string {} /** - * Writes the log to the stream itself + * Constructor. Accepts the name and some options * - * @param string $message - * @param int $type - * @param int $time - * @param array $context + * @param string $name + * @param array $options */ - public function logInternal($message, $type, $time, array $context) {} + public function __construct(string $name, array $options = array()) {} /** - * Closes the logger + * Closes the stream * * @return bool */ - public function close() {} + public function close(): bool {} + + /** + * Processes the message i.e. writes it to the file + * + * @param \Phalcon\Logger\Item $item + */ + public function process(\Phalcon\Logger\Item $item) {} } diff --git a/src/Phalcon/logger/adapter/Syslog.php b/src/Phalcon/logger/adapter/Syslog.php index bf684c7c..14c95796 100644 --- a/src/Phalcon/logger/adapter/Syslog.php +++ b/src/Phalcon/logger/adapter/Syslog.php @@ -7,7 +7,7 @@ * * Sends logs to the system logger * - * + * ```php * use Phalcon\Logger; * use Phalcon\Logger\Adapter\Syslog; * @@ -23,12 +23,36 @@ * $logger->log("This is a message"); * $logger->log(Logger::ERROR, "This is an error"); * $logger->error("This is another error"); - * + * ``` */ -class Syslog extends \Phalcon\Logger\Adapter +class Syslog extends \Phalcon\Logger\Adapter\AbstractAdapter { + /** + * Name of the default formatter class + * + * @var string + */ + protected $defaultFormatter = 'Syslog'; + + /** + * @var int + */ + protected $facility = 0; + + /** + * @var string + */ + protected $name = ''; - protected $_opened = false; + /** + * @var bool + */ + protected $opened = false; + + /** + * @var int + */ + protected $option = 0; /** @@ -37,30 +61,28 @@ class Syslog extends \Phalcon\Logger\Adapter * @param string $name * @param array $options */ - public function __construct($name, $options = null) {} + public function __construct(string $name, array $options = array()) {} /** - * Returns the internal formatter + * Closes the logger * - * @return \Phalcon\Logger\FormatterInterface + * @return bool */ - public function getFormatter() {} + public function close(): bool {} /** - * Writes the log to the stream itself + * Processes the message i.e. writes it to the syslog * - * @param string $message - * @param int $type - * @param int $time - * @param array $context + * @param \Phalcon\Logger\Item $item */ - public function logInternal($message, $type, $time, array $context) {} + public function process(\Phalcon\Logger\Item $item) {} /** - * Closes the logger + * Translates a Logger level to a Syslog level * - * @return bool + * @param string $level + * @return int */ - public function close() {} + private function logLevelToSyslog(string $level): int {} } diff --git a/src/Phalcon/logger/formatter/AbstractFormatter.php b/src/Phalcon/logger/formatter/AbstractFormatter.php new file mode 100644 index 00000000..9049eb11 --- /dev/null +++ b/src/Phalcon/logger/formatter/AbstractFormatter.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +abstract class AbstractFormatter implements \Phalcon\Logger\Formatter\FormatterInterface +{ + + /** + * Interpolates context values into the message placeholders + * + * @see http://www.php-fig.org/psr/psr-3/ Section 1.2 Message + * @param string $message + * @param array $context + */ + public function interpolate(string $message, $context = null) {} + +} diff --git a/src/Phalcon/logger/formatter/Abstractformatter.php b/src/Phalcon/logger/formatter/Abstractformatter.php deleted file mode 100644 index 1079548e..00000000 --- a/src/Phalcon/logger/formatter/Abstractformatter.php +++ /dev/null @@ -1,19 +0,0 @@ - item - * - * @return string|array - */ - public function format(Item $item); -} + /** + * Applies a format to an item + * + * @param \Phalcon\Logger\Item $item + * @return string|array + */ + public function format(\Phalcon\Logger\Item $item); + +} diff --git a/src/Phalcon/logger/formatter/Json.php b/src/Phalcon/logger/formatter/Json.php index 127cb1bd..a1552d6a 100644 --- a/src/Phalcon/logger/formatter/Json.php +++ b/src/Phalcon/logger/formatter/Json.php @@ -7,18 +7,43 @@ * * Formats messages using JSON encoding */ -class Json extends \Phalcon\Logger\Formatter +class Json extends \Phalcon\Logger\Formatter\AbstractFormatter { + /** + * Default date format + * + * @var string + */ + protected $dateFormat; + + + /** + * Default date format + * + * @return string + */ + public function getDateFormat(): string {} + + /** + * Default date format + * + * @param string $dateFormat + */ + public function setDateFormat(string $dateFormat) {} + + /** + * Phalcon\Logger\Formatter\Json construct + * + * @param string $dateFormat + */ + public function __construct(string $dateFormat = 'D, d M y H:i:s O') {} /** * Applies a format to a message before sent it to the internal log * - * @param string $message - * @param int $type - * @param int $timestamp - * @param array $context + * @param \Phalcon\Logger\Item $item * @return string */ - public function format($message, $type, $timestamp, $context = null) {} + public function format(\Phalcon\Logger\Item $item): string {} } diff --git a/src/Phalcon/logger/formatter/Line.php b/src/Phalcon/logger/formatter/Line.php index 0387d9ed..b575d37d 100644 --- a/src/Phalcon/logger/formatter/Line.php +++ b/src/Phalcon/logger/formatter/Line.php @@ -7,21 +7,21 @@ * * Formats messages using an one-line string */ -class Line extends \Phalcon\Logger\Formatter +class Line extends \Phalcon\Logger\Formatter\AbstractFormatter { /** * Default date format * * @var string */ - protected $_dateFormat = 'D, d M y H:i:s O'; + protected $dateFormat; /** * Format applied to each message * * @var string */ - protected $_format = '[%date%][%type%] %message%'; + protected $format; /** @@ -29,28 +29,28 @@ class Line extends \Phalcon\Logger\Formatter * * @return string */ - public function getDateFormat() {} + public function getDateFormat(): string {} /** * Default date format * * @param string $dateFormat */ - public function setDateFormat($dateFormat) {} + public function setDateFormat(string $dateFormat) {} /** * Format applied to each message * * @return string */ - public function getFormat() {} + public function getFormat(): string {} /** * Format applied to each message * * @param string $format */ - public function setFormat($format) {} + public function setFormat(string $format) {} /** * Phalcon\Logger\Formatter\Line construct @@ -58,17 +58,14 @@ public function setFormat($format) {} * @param string $format * @param string $dateFormat */ - public function __construct($format = null, $dateFormat = null) {} + public function __construct(string $format = '[%date%][%type%] %message%', string $dateFormat = 'D, d M y H:i:s O') {} /** * Applies a format to a message before sent it to the internal log * - * @param string $message - * @param int $type - * @param int $timestamp - * @param array $context + * @param \Phalcon\Logger\Item $item * @return string */ - public function format($message, $type, $timestamp, $context = null) {} + public function format(\Phalcon\Logger\Item $item): string {} } diff --git a/src/Phalcon/logger/formatter/Syslog.php b/src/Phalcon/logger/formatter/Syslog.php index c37da150..6f886239 100644 --- a/src/Phalcon/logger/formatter/Syslog.php +++ b/src/Phalcon/logger/formatter/Syslog.php @@ -7,18 +7,15 @@ * * Prepares a message to be used in a Syslog backend */ -class Syslog extends \Phalcon\Logger\Formatter +class Syslog extends \Phalcon\Logger\Formatter\AbstractFormatter { /** * Applies a format to a message before sent it to the internal log * - * @param string $message - * @param int $type - * @param int $timestamp - * @param array $context + * @param \Phalcon\Logger\Item $item * @return array */ - public function format($message, $type, $timestamp, $context = null) {} + public function format(\Phalcon\Logger\Item $item): array {} } diff --git a/src/Phalcon/messages/Exception.php b/src/Phalcon/messages/Exception.php index b1978f3b..bca86886 100644 --- a/src/Phalcon/messages/Exception.php +++ b/src/Phalcon/messages/Exception.php @@ -5,8 +5,7 @@ /** * Phalcon\Validation\Exception * - * Exceptions thrown in Phalcon\Messages\* classes will use this class - * + * Exceptions thrown in Phalcon\Messages\ classes will use this class */ class Exception extends \Phalcon\Exception { diff --git a/src/Phalcon/messages/Message.php b/src/Phalcon/messages/Message.php index 3cfe5cfe..e1d94052 100644 --- a/src/Phalcon/messages/Message.php +++ b/src/Phalcon/messages/Message.php @@ -2,137 +2,127 @@ namespace Phalcon\Messages; -use Phalcon\Messages\MessageInterface; - /** * Phalcon\Messages\Message * * Stores a message from various components */ -class Message implements MessageInterface, \JsonSerializable +class Message implements \Phalcon\Messages\MessageInterface, \JsonSerializable { - /** - * @var int - */ - protected $code; - - /** - * @var string - */ - protected $field; - - /** - * @var string - */ - protected $message; - - /** - * @var string - */ - protected $type; - - /** - * @var array - */ - protected $metaData = []; - - /** - * Phalcon\Messages\Message constructor - */ - public function __construct(string $message, $field = "", string $type = "", int $code = 0, array $metaData = []) - { - } - - /** - * Returns the message code - */ - public function getCode() : int - { - } - - /** - * Returns field name related to message - * - * @return mixed - */ - public function getField() - { - } - - /** - * Returns verbose message - */ - public function getMessage() : string - { - } - - /** - * Returns message type - */ - public function getType() : string - { - } - - /** - * Returns message metadata - */ - public function getMetaData() : array - { - } - - /** - * Serializes the object for json_encode - */ - public function jsonSerialize() : array - { - } - - /** - * Sets code for the message - */ - public function setCode(int $code) : MessageInterface - { - } - - /** - * Sets field name related to message - */ - public function setField($field) : MessageInterface - { - } - - /** - * Sets verbose message - */ - public function setMessage(string $message) : MessageInterface - { - } - - /** - * Sets message type - */ - public function setType(string $type) : MessageInterface - { - } - - /** - * Sets message metadata - */ - public function setMetaData(array $metaData) : MessageInterface - { - } - - /** - * Magic __toString method returns verbose message - */ - public function __toString() : string - { - } - - /** - * Magic __set_state helps to re-build messages variable exporting - */ - public static function __set_state(array $message) : MessageInterface - { - } + /** + * @var int + */ + protected $code; + + /** + * @var string + */ + protected $field; + + /** + * @var string + */ + protected $message; + + /** + * @var string + */ + protected $type; + + /** + * @var array + */ + protected $metaData = array(); + + + /** + * @return int + */ + public function getCode(): int {} + + /** + * @return string + */ + public function getField(): string {} + + /** + * @return string + */ + public function getMessage(): string {} + + /** + * @return string + */ + public function getType(): string {} + + /** + * @return array + */ + public function getMetaData(): array {} + + /** + * Phalcon\Messages\Message constructor + * + * @param string $message + * @param mixed $field + * @param string $type + * @param int $code + * @param array $metaData + */ + public function __construct(string $message, $field = '', string $type = '', int $code = 0, array $metaData = array()) {} + + /** + * Magic __toString method returns verbose message + * + * @return string + */ + public function __toString(): string {} + + /** + * Serializes the object for json_encode + * + * @return array + */ + public function jsonSerialize(): array {} + + /** + * Sets code for the message + * + * @param int $code + * @return \Phalcon\Messages\MessageInterface + */ + public function setCode(int $code): MessageInterface {} + + /** + * Sets field name related to message + * + * @param mixed $field + * @return \Phalcon\Messages\MessageInterface + */ + public function setField($field): MessageInterface {} + + /** + * Sets verbose message + * + * @param string $message + * @return \Phalcon\Messages\MessageInterface + */ + public function setMessage(string $message): MessageInterface {} + + /** + * Sets message metadata + * + * @param array $metaData + * @return \Phalcon\Messages\MessageInterface + */ + public function setMetaData(array $metaData): MessageInterface {} + + /** + * Sets message type + * + * @param string $type + * @return \Phalcon\Messages\MessageInterface + */ + public function setType(string $type): MessageInterface {} + } diff --git a/src/Phalcon/messages/MessageInterface.php b/src/Phalcon/messages/MessageInterface.php new file mode 100644 index 00000000..550abcfa --- /dev/null +++ b/src/Phalcon/messages/MessageInterface.php @@ -0,0 +1,95 @@ + - * $messages->appendMessage( - * new \Phalcon\Messages\Message("This is a message") - * ); - * - */ - public function appendMessage(MessageInterface $message) - { - } - - /** - * Appends an array of messages to the collection - * - * - * $messages->appendMessages($messagesArray); - * - * - * @param \Phalcon\Messages\MessageInterface[] messages - */ - public function appendMessages($messages) - { - } - - /** - * Returns the number of messages in the list - */ - public function count() : int - { - } - - /** - * Returns the current message in the iterator - */ - public function current() : MessageInterface - { - } - - /** - * Filters the message collection by field name - */ - public function filter(string $fieldName) : array - { - } + /** + * @var int + */ + protected $position = 0; + + /** + * @var array + */ + protected $messages; + + + /** + * Phalcon\Messages\Messages constructor + * + * @param array $messages + */ + public function __construct(array $messages = array()) {} + + /** + * Appends a message to the collection + * + * ```php + * $messages->appendMessage( + * new \Phalcon\Messages\Message("This is a message") + * ); + * ``` + * + * @param \Phalcon\Messages\MessageInterface $message + */ + public function appendMessage(\Phalcon\Messages\MessageInterface $message) {} + + /** + * Appends an array of messages to the collection + * + * ```php + * $messages->appendMessages($messagesArray); + * ``` + * + * @param \Phalcon\Messages\MessageInterface[] $messages + */ + public function appendMessages($messages) {} + + /** + * Returns the number of messages in the list + * + * @return int + */ + public function count(): int {} + + /** + * Returns the current message in the iterator + * + * @return \Phalcon\Messages\MessageInterface + */ + public function current(): MessageInterface {} + + /** + * Filters the message collection by field name + * + * @param string $fieldName + * @return array + */ + public function filter(string $fieldName): array {} /** * Returns serialised message objects as array for json_encode. Calls * jsonSerialize on each object if present * - * + * ```php * $data = $messages->jsonSerialize(); * echo json_encode($data); - * - */ - public function jsonSerialize() : array - { - } - - /** - * Returns the current position/key in the iterator - */ - public function key() : int - { - } - - /** - * Moves the internal iteration pointer to the next position - */ - public function next() : void - { - } - - /** - * Checks if an index exists - * - * - * var_dump( - * isset($message["database"]) - * ); - * - * - * @param int index - */ - public function offsetExists($index) : boolean - { - } - - /** - * Gets an attribute a message using the array syntax - * - * - * print_r( - * $messages[0] - * ); - * - */ - public function offsetGet($index) { - } - - /** - * Sets an attribute using the array-syntax - * - * - * $messages[0] = new \Phalcon\Messages\Message("This is a message"); - * - * - * @param \Phalcon\Messages\Message message - */ - public function offsetSet($index, $message) : void - { - } - - /** - * Removes a message from the list - * - * - * unset($message["database"]); - * - */ - public function offsetUnset($index) : void - { - } - - /** - * Rewinds the internal iterator - */ - public function rewind() : void - { - } - - /** - * Check if the current message in the iterator is valid - */ - public function valid() : boolean - { - } + * ``` + * + * @return array + */ + public function jsonSerialize(): array {} + + /** + * Returns the current position/key in the iterator + * + * @return int + */ + public function key(): int {} + + /** + * Moves the internal iteration pointer to the next position + */ + public function next() {} + + /** + * Checks if an index exists + * + * ```php + * var_dump( + * isset($message["database"]) + * ); + * ``` + * + * @param int $index + * @return bool + */ + public function offsetExists($index): bool {} + + /** + * Gets an attribute a message using the array syntax + * + * ```php + * print_r( + * $messages[0] + * ); + * ``` + * + * @param mixed $index + * @return mixed + */ + public function offsetGet($index) {} + + /** + * Sets an attribute using the array-syntax + * + * ```php + * $messages[0] = new \Phalcon\Messages\Message("This is a message"); + * ``` + * + * @param mixed $index + * @param \Phalcon\Messages\Message $message + */ + public function offsetSet($index, $message) {} + + /** + * Removes a message from the list + * + * ```php + * unset($message["database"]); + * ``` + * + * @param mixed $index + */ + public function offsetUnset($index) {} + + /** + * Rewinds the internal iterator + */ + public function rewind() {} + + /** + * Check if the current message in the iterator is valid + * + * @return bool + */ + public function valid(): bool {} + } diff --git a/src/Phalcon/mvc/Application.php b/src/Phalcon/mvc/Application.php index 293a9d9d..9faf4966 100644 --- a/src/Phalcon/mvc/Application.php +++ b/src/Phalcon/mvc/Application.php @@ -5,10 +5,11 @@ /** * Phalcon\Mvc\Application * - * This component encapsulates all the complex operations behind instantiating every component - * needed and integrating it with the rest to allow the MVC pattern to operate as desired. + * This component encapsulates all the complex operations behind instantiating + * every component needed and integrating it with the rest to allow the MVC + * pattern to operate as desired. * - * + * ```php * use Phalcon\Mvc\Application; * * class MyApp extends Application @@ -45,27 +46,27 @@ * $application = new MyApp(); * * $application->main(); - * + * ``` */ -class Application extends \Phalcon\Application +class Application extends \Phalcon\Application\AbstractApplication { - protected $_implicitView = true; + protected $implicitView = true; - protected $_sendHeaders = true; + protected $sendCookies = true; - protected $_sendCookies = true; + protected $sendHeaders = true; /** - * Enables or disables sending headers by each request handling + * Handles a MVC request * - * @param bool $sendHeaders - * @return Application + * @param string $uri + * @return bool|\Phalcon\Http\ResponseInterface */ - public function sendHeadersOnHandleRequest($sendHeaders) {} + public function handle(string $uri) {} /** * Enables or disables sending cookies by each request handling @@ -73,23 +74,23 @@ public function sendHeadersOnHandleRequest($sendHeaders) {} * @param bool $sendCookies * @return Application */ - public function sendCookiesOnHandleRequest($sendCookies) {} + public function sendCookiesOnHandleRequest(bool $sendCookies): Application {} /** - * By default. The view is implicitly buffering all the output - * You can full disable the view component using this method + * Enables or disables sending headers by each request handling * - * @param bool $implicitView + * @param bool $sendHeaders * @return Application */ - public function useImplicitView($implicitView) {} + public function sendHeadersOnHandleRequest(bool $sendHeaders): Application {} /** - * Handles a MVC request + * By default. The view is implicitly buffering all the output + * You can full disable the view component using this method * - * @param string $uri - * @return bool|\Phalcon\Http\ResponseInterface + * @param bool $implicitView + * @return Application */ - public function handle($uri = null) {} + public function useImplicitView(bool $implicitView): Application {} } diff --git a/src/Phalcon/mvc/Collection.php b/src/Phalcon/mvc/Collection.php index 14296c3d..a5dbf4ae 100644 --- a/src/Phalcon/mvc/Collection.php +++ b/src/Phalcon/mvc/Collection.php @@ -11,160 +11,336 @@ abstract class Collection implements \Phalcon\Mvc\EntityInterface, \Phalcon\Mvc\CollectionInterface, \Phalcon\Di\InjectionAwareInterface, \Serializable { - const OP_NONE = 0; + const DIRTY_STATE_DETACHED = 2; - const OP_CREATE = 1; + const DIRTY_STATE_PERSISTENT = 0; - const OP_UPDATE = 2; + const DIRTY_STATE_TRANSIENT = 1; - const OP_DELETE = 3; + const OP_CREATE = 1; - const DIRTY_STATE_PERSISTENT = 0; + const OP_DELETE = 3; - const DIRTY_STATE_TRANSIENT = 1; + const OP_NONE = 0; - const DIRTY_STATE_DETACHED = 2; + const OP_UPDATE = 2; public $_id; - protected $_dependencyInjector; + protected $connection; - protected $_modelsManager; + protected $container; - protected $_source; + protected $dirtyState = 1; - protected $_operationMade = 0; + static protected $disableEvents; - protected $_dirtyState = 1; + protected $errorMessages = array(); - protected $_connection; + protected $modelsManager; - protected $_errorMessages = array(); + protected $operationMade = 0; - static protected $_reserved; + static protected $reserved; - static protected $_disableEvents; + protected $skipped = false; - protected $_skipped = false; + protected $source; /** * Phalcon\Mvc\Collection constructor * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @param \Phalcon\Mvc\Collection\ManagerInterface $modelsManager */ - public final function __construct(\Phalcon\DiInterface $dependencyInjector = null, \Phalcon\Mvc\Collection\ManagerInterface $modelsManager = null) {} + final public function __construct(\Phalcon\Di\DiInterface $container = null, \Phalcon\Mvc\Collection\ManagerInterface $modelsManager = null) {} /** - * Sets a value for the _id property, creates a MongoId object if needed + * Sets up a behavior in a collection * - * @param mixed $id + * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior */ - public function setId($id) {} + protected function addBehavior(\Phalcon\Mvc\Collection\BehaviorInterface $behavior) {} /** - * Returns the value of the _id property + * Perform an aggregation using the Mongo aggregation framework * - * @return \MongoId + * @param array $parameters + * @param array $options + * @return array */ - public function getId() {} + public static function aggregate(array $parameters = null, array $options = null): array {} /** - * Sets the dependency injection container + * Appends a customized message on the validation process + * + * ```php + * use \Phalcon\Messages\Message as Message; + * + * class Robots extends \Phalcon\Mvc\Model + * { + * public function beforeSave() + * { + * if ($this->name === "Peter") { + * $message = new Message( + * "Sorry, but a robot cannot be named Peter" + * ); + * + * $this->appendMessage(message); + * } + * } + * } + * ``` * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Messages\MessageInterface $message */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function appendMessage(\Phalcon\Messages\MessageInterface $message) {} /** - * Returns the dependency injection container + * Returns a cloned collection * - * @return \Phalcon\DiInterface + * @param CollectionInterface $collection + * @param array $document + * @return CollectionInterface */ - public function getDI() {} + public static function cloneResult(CollectionInterface $collection, array $document): CollectionInterface {} /** - * Sets a custom events manager + * Creates a collection based on the values in the attributes * - * @param \Phalcon\Mvc\Collection\ManagerInterface $eventsManager + * @return bool */ - protected function setEventsManager(\Phalcon\Mvc\Collection\ManagerInterface $eventsManager) {} + public function create(): bool {} /** - * Returns the custom events manager + * Creates a document based on the values in the attributes, if not found by + * criteria. Preferred way to avoid duplication is to create index o + * attribute * - * @return \Phalcon\Mvc\Collection\ManagerInterface + * ```php + * $robot = new Robot(); + * + * $robot->name = "MyRobot"; + * $robot->type = "Droid"; + * + * // Create only if robot with same name and type does not exist + * $robot->createIfNotExist( + * [ + * "name", + * "type", + * ] + * ); + * ``` + * + * @param array $criteria + * @return bool */ - protected function getEventsManager() {} + public function createIfNotExist(array $criteria): bool {} /** - * Returns the models manager related to the entity instance + * Perform a count over a collection * - * @return \Phalcon\Mvc\Collection\ManagerInterface + * ```php + * echo "There are ", Robots::count(), " robots"; + * ``` + * + * @param array $parameters + * @return int + */ + public static function count(array $parameters = null): int {} + + /** + * Deletes a model instance. Returning true on success or false otherwise. + * + * ```php + * $robot = Robots::findFirst(); + * + * $robot->delete(); + * + * $robots = Robots::find(); + * + * foreach ($robots as $robot) { + * $robot->delete(); + * } + * ``` + * + * @return bool */ - public function getCollectionManager() {} + public function delete(): bool {} /** - * Returns an array with reserved properties that cannot be part of the insert/update + * Allows to query a set of records that match the specified conditions + * + * ```php + * // How many robots are there? + * $robots = Robots::find(); + * + * echo "There are ", count($robots), "\n"; + * + * // How many mechanical robots are there? + * $robots = Robots::find( + * [ + * [ + * "type" => "mechanical", + * ] + * ] + * ); + * + * echo "There are ", count(robots), "\n"; + * + * // Get and print virtual robots ordered by name + * $robots = Robots::findFirst( + * [ + * [ + * "type" => "virtual" + * ], + * "order" => [ + * "name" => 1, + * ] + * ] + * ); + * + * foreach ($robots as $robot) { + * echo $robot->name, "\n"; + * } + * + * // Get first 100 virtual robots ordered by name + * $robots = Robots::find( + * [ + * [ + * "type" => "virtual", + * ], + * "order" => [ + * "name" => 1, + * ], + * "limit" => 100, + * ] + * ); + * + * foreach ($robots as $robot) { + * echo $robot->name, "\n"; + * } + * ``` * + * @param array $parameters * @return array */ - public function getReservedAttributes() {} + public static function find(array $parameters = null): array {} /** - * Sets if a model must use implicit objects ids + * Find a document by its id (_id) * - * @param bool $useImplicitObjectIds + * ```php + * // Find user by using \MongoId object + * $user = Users::findById( + * new \MongoId("545eb081631d16153a293a66") + * ); + * + * // Find user by using id as sting + * $user = Users::findById("45cbc4a0e4123f6920000002"); + * + * // Validate input + * if ($user = Users::findById($_POST["id"])) { + * // ... + * } + * ``` + * + * @param mixed $id + * @return null|CollectionInterface */ - protected function useImplicitObjectIds($useImplicitObjectIds) {} + public static function findById($id): ?CollectionInterface {} /** - * Sets collection name which model should be mapped + * Allows to query the first record that match the specified conditions * - * @param string $source - * @return Collection + * ```php + * // What's the first robot in the robots table? + * $robot = Robots::findFirst(); + * + * echo "The robot name is ", $robot->name, "\n"; + * + * // What's the first mechanical robot in robots table? + * $robot = Robots::findFirst( + * [ + * [ + * "type" => "mechanical", + * ] + * ] + * ); + * + * echo "The first mechanical robot name is ", $robot->name, "\n"; + * + * // Get first virtual robot ordered by name + * $robot = Robots::findFirst( + * [ + * [ + * "type" => "mechanical", + * ], + * "order" => [ + * "name" => 1, + * ], + * ] + * ); + * + * echo "The first virtual robot name is ", $robot->name, "\n"; + * + * // Get first robot by id (_id) + * $robot = Robots::findFirst( + * [ + * [ + * "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + * ] + * ] + * ); + * + * echo "The robot id is ", $robot->_id, "\n"; + * ``` + * + * @param array $parameters + * @return array */ - protected function setSource($source) {} + public static function findFirst(array $parameters = null): array {} /** - * Returns collection name mapped in the model + * Fires an internal event * - * @return string + * @param string $eventName + * @return bool */ - public function getSource() {} + public function fireEvent(string $eventName): bool {} /** - * Sets the DependencyInjection connection service name + * Fires an internal event that cancels the operation * - * @param string $connectionService - * @return Collection + * @param string $eventName + * @return bool */ - public function setConnectionService($connectionService) {} + public function fireEventCancel(string $eventName): bool {} /** - * Returns DependencyInjection connection service + * Returns the models manager related to the entity instance * - * @return string + * @return \Phalcon\Mvc\Collection\ManagerInterface */ - public function getConnectionService() {} + public function getCollectionManager(): ManagerInterface {} /** * Retrieves a database connection @@ -174,534 +350,315 @@ public function getConnectionService() {} public function getConnection() {} /** - * Reads an attribute value by its name - * - * - * echo $robot->readAttribute("name"); - * + * Returns DependencyInjection connection service * - * @param string $attribute - * @return mixed + * @return string */ - public function readAttribute($attribute) {} + public function getConnectionService(): string {} /** - * Writes an attribute value by its name - * - * - * $robot->writeAttribute("name", "Rosey"); - * + * Returns the dependency injection container * - * @param string $attribute - * @param mixed $value + * @return \Phalcon\Di\DiInterface */ - public function writeAttribute($attribute, $value) {} + public function getDI(): DiInterface {} /** - * Returns a cloned collection + * Returns one of the DIRTY_STATE_ constants telling if the document exists + * in the collection or not * - * @param CollectionInterface $collection - * @param array $document - * @return CollectionInterface + * @return int */ - public static function cloneResult(CollectionInterface $collection, array $document) {} + public function getDirtyState(): int {} /** - * Returns a collection resultset + * Returns the custom events manager * - * @param array $params - * @param \Phalcon\Mvc\Collection $collection - * @param \MongoDb $connection - * @param boolean $unique - * @return array + * @return \Phalcon\Mvc\Collection\ManagerInterface */ - protected static function _getResultset($params, CollectionInterface $collection, $connection, $unique) {} + protected function getEventsManager(): ManagerInterface {} /** - * Perform a count over a resultset + * Returns the value of the _id property * - * @param array $params - * @param \Phalcon\Mvc\Collection $collection - * @param \MongoDb $connection - * @return int + * @return \MongoId */ - protected static function _getGroupResultset($params, Collection $collection, $connection) {} + public function getId() {} /** - * Executes internal hooks before save a document + * Returns all the validation messages * - * @param \Phalcon\DiInterface $dependencyInjector - * @param boolean $disableEvents - * @param boolean $exists - * @return bool - */ - protected final function _preSave($dependencyInjector, $disableEvents, $exists) {} - - /** - * Executes internal events after save a document - * - * @param bool $disableEvents - * @param bool $success - * @param bool $exists - * @return bool - */ - protected final function _postSave($disableEvents, $success, $exists) {} - - /** - * Executes validators on every validation call - * - * - * use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * // Old, deprecated syntax, use new one below - * $this->validate( - * new ExclusionIn( - * [ - * "field" => "status", - * "domain" => ["A", "I"], - * ] - * ) - * ); + * ```php + * $robot = new Robots(); * - * if ($this->validationHasFailed() == true) { - * return false; - * } - * } - * } - * + * $robot->type = "mechanical"; + * $robot->name = "Astro Boy"; + * $robot->year = 1952; * - * - * use Phalcon\Validation\Validator\ExclusionIn as ExclusionIn; - * use Phalcon\Validation; + * if ($robot->save() === false) { + * echo "Umh, We can't store robots right now "; * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $validator = new Validation(); - * $validator->add("status", - * new ExclusionIn( - * [ - * "domain" => ["A", "I"] - * ] - * ) - * ); + * $messages = $robot->getMessages(); * - * return $this->validate($validator); + * foreach ($messages as $message) { + * echo $message; * } + * } else { + * echo "Great, a new robot was saved successfully!"; * } - * + * ``` * - * @param mixed $validator + * @return array|\Phalcon\Messages\MessageInterface[] */ - protected function validate($validator) {} + public function getMessages(): array {} /** - * Check whether validation process has generated any messages + * Returns an array with reserved properties that cannot be part of the + * insert/update * - * - * use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new ExclusionIn( - * [ - * "field" => "status", - * "domain" => ["A", "I"], - * ] - * ) - * ); - * - * if ($this->validationHasFailed() == true) { - * return false; - * } - * } - * } - * - * - * @return bool + * @return array */ - public function validationHasFailed() {} + public function getReservedAttributes(): array {} /** - * Fires an internal event + * Returns collection name mapped in the model * - * @param string $eventName - * @return bool + * @return string */ - public function fireEvent($eventName) {} + public function getSource(): string {} /** - * Fires an internal event that cancels the operation + * Reads an attribute value by its name * - * @param string $eventName - * @return bool - */ - public function fireEventCancel($eventName) {} - - /** - * Cancel the current operation + * ```php + * echo $robot->readAttribute("name"); + * ``` * - * @param bool $disableEvents - * @return bool + * @param string $attribute + * @return mixed|null */ - protected function _cancelOperation($disableEvents) {} + public function readAttribute(string $attribute): ? {} /** - * Checks if the document exists in the collection + * Creates/Updates a collection based on the values in the attributes * - * @param \MongoCollection $collection * @return bool */ - protected function _exists($collection) {} + public function save(): bool {} /** - * Returns all the validation messages - * - * - * $robot = new Robots(); - * - * $robot->type = "mechanical"; - * $robot->name = "Astro Boy"; - * $robot->year = 1952; - * - * if ($robot->save() === false) { - * echo "Umh, We can't store robots right now "; - * - * $messages = $robot->getMessages(); - * - * foreach ($messages as $message) { - * echo $message; - * } - * } else { - * echo "Great, a new robot was saved successfully!"; - * } - * + * Serializes the object ignoring connections or protected properties * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return string */ - public function getMessages() {} + public function serialize(): string {} /** - * Appends a customized message on the validation process - * - * - * use \Phalcon\Mvc\Model\Message as Message; - * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function beforeSave() - * { - * if ($this->name === "Peter") { - * $message = new Message( - * "Sorry, but a robot cannot be named Peter" - * ); - * - * $this->appendMessage(message); - * } - * } - * } - * + * Sets the DependencyInjection connection service name * - * @param \Phalcon\Mvc\Model\MessageInterface $message + * @param string $connectionService + * @return Collection */ - public function appendMessage(\Phalcon\Mvc\Model\MessageInterface $message) {} + public function setConnectionService(string $connectionService): Collection {} /** - * Shared Code for CU Operations - * Prepares Collection + * Sets the dependency injection container + * + * @param \Phalcon\Di\DiInterface $container */ - protected function prepareCU() {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Creates/Updates a collection based on the values in the attributes + * Sets the dirty state of the object using one of the DIRTY_STATE_ + * constants * - * @return bool + * @param int $dirtyState + * @return CollectionInterface */ - public function save() {} + public function setDirtyState(int $dirtyState): CollectionInterface {} /** - * Creates a collection based on the values in the attributes + * Sets a custom events manager * - * @return bool + * @param \Phalcon\Mvc\Collection\ManagerInterface $eventsManager */ - public function create() {} + protected function setEventsManager(\Phalcon\Mvc\Collection\ManagerInterface $eventsManager) {} /** - * Creates a document based on the values in the attributes, if not found by criteria - * Preferred way to avoid duplication is to create index on attribute - * - * - * $robot = new Robot(); - * - * $robot->name = "MyRobot"; - * $robot->type = "Droid"; - * - * // Create only if robot with same name and type does not exist - * $robot->createIfNotExist( - * [ - * "name", - * "type", - * ] - * ); - * + * Sets a value for the _id property, creates a MongoId object if needed * - * @param array $criteria - * @return bool + * @param mixed $id */ - public function createIfNotExist(array $criteria) {} + public function setId($id) {} /** - * Creates/Updates a collection based on the values in the attributes + * Sets collection name which model should be mapped * - * @return bool + * @param string $source + * @return Collection */ - public function update() {} + protected function setSource(string $source): Collection {} /** - * Find a document by its id (_id) - * - * - * // Find user by using \MongoId object - * $user = Users::findById( - * new \MongoId("545eb081631d16153a293a66") - * ); - * - * // Find user by using id as sting - * $user = Users::findById("45cbc4a0e4123f6920000002"); - * - * // Validate input - * if ($user = Users::findById($_POST["id"])) { - * // ... - * } - * + * Skips the current operation forcing a success state * - * @param mixed $id - * @return null|CollectionInterface + * @param bool $skip */ - public static function findById($id) {} + public function skipOperation(bool $skip) {} /** - * Allows to query the first record that match the specified conditions - * - * - * // What's the first robot in the robots table? - * $robot = Robots::findFirst(); - * - * echo "The robot name is ", $robot->name, "\n"; - * - * // What's the first mechanical robot in robots table? - * $robot = Robots::findFirst( - * [ - * [ - * "type" => "mechanical", - * ] - * ] - * ); - * - * echo "The first mechanical robot name is ", $robot->name, "\n"; - * - * // Get first virtual robot ordered by name - * $robot = Robots::findFirst( - * [ - * [ - * "type" => "mechanical", - * ], - * "order" => [ - * "name" => 1, - * ], - * ] - * ); - * - * echo "The first virtual robot name is ", $robot->name, "\n"; - * - * // Get first robot by id (_id) - * $robot = Robots::findFirst( - * [ - * [ - * "_id" => new \MongoId("45cbc4a0e4123f6920000002"), - * ] - * ] - * ); - * - * echo "The robot id is ", $robot->_id, "\n"; - * + * Allows to perform a summatory group for a column in the collection * - * @param array $parameters + * @param string $field + * @param mixed $conditions + * @param mixed $finalize * @return array */ - public static function findFirst(array $parameters = null) {} + public static function summatory(string $field, $conditions = null, $finalize = null): array {} /** - * Allows to query a set of records that match the specified conditions - * - * - * // How many robots are there? - * $robots = Robots::find(); - * - * echo "There are ", count($robots), "\n"; - * - * // How many mechanical robots are there? - * $robots = Robots::find( - * [ - * [ - * "type" => "mechanical", - * ] - * ] - * ); - * - * echo "There are ", count(robots), "\n"; - * - * // Get and print virtual robots ordered by name - * $robots = Robots::findFirst( - * [ - * [ - * "type" => "virtual" - * ], - * "order" => [ - * "name" => 1, - * ] - * ] - * ); - * - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } + * Returns the instance as an array representation * - * // Get first 100 virtual robots ordered by name - * $robots = Robots::find( - * [ - * [ - * "type" => "virtual", - * ], - * "order" => [ - * "name" => 1, - * ], - * "limit" => 100, - * ] + * ```php + * print_r( + * $robot->toArray() * ); + * ``` * - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; - * } - * - * - * @param array $parameters * @return array */ - public static function find(array $parameters = null) {} - - /** - * Perform a count over a collection - * - * - * echo "There are ", Robots::count(), " robots"; - * - * - * @param array $parameters - * @return int - */ - public static function count(array $parameters = null) {} + public function toArray(): array {} /** - * Perform an aggregation using the Mongo aggregation framework + * Unserializes the object from a serialized string * - * @param array $parameters - * @param array $options - * @return array + * @param mixed $data */ - public static function aggregate(array $parameters = null, array $options = null) {} + public function unserialize($data) {} /** - * Allows to perform a summatory group for a column in the collection + * Creates/Updates a collection based on the values in the attributes * - * @param string $field - * @param mixed $conditions - * @param mixed $finalize - * @return array + * @return bool */ - public static function summatory($field, $conditions = null, $finalize = null) {} + public function update(): bool {} /** - * Deletes a model instance. Returning true on success or false otherwise. + * Executes validators on every validation call * - * - * $robot = Robots::findFirst(); + * ```php + * use Phalcon\Mvc\Collection; + * use Phalcon\Validation; + * use Phalcon\Validation\Validator\ExclusionIn; * - * $robot->delete(); + * class Subscriptors extends Collection + * { + * public function validation() + * { + * $validator = new Validation(); * - * $robots = Robots::find(); + * $validator->add( + * "status", + * new ExclusionIn( + * [ + * "domain" => [ + * "A", + * "I", + * ], + * ] + * ) + * ); * - * foreach ($robots as $robot) { - * $robot->delete(); + * return $this->validate($validator); + * } * } - * + * ``` * + * @param \Phalcon\Validation\ValidationInterface $validator * @return bool */ - public function delete() {} + protected function validate(\Phalcon\Validation\ValidationInterface $validator): bool {} /** - * Sets the dirty state of the object using one of the DIRTY_STATE_ constants + * Sets if a model must use implicit objects ids * - * @param int $dirtyState - * @return CollectionInterface + * @param bool $useImplicitObjectIds */ - public function setDirtyState($dirtyState) {} + protected function useImplicitObjectIds(bool $useImplicitObjectIds) {} /** - * Returns one of the DIRTY_STATE_ constants telling if the document exists in the collection or not + * Writes an attribute value by its name * - * @return int + * ```php + * $robot->writeAttribute("name", "Rosey"); + * ``` + * + * @param string $attribute + * @param mixed $value */ - public function getDirtyState() {} + public function writeAttribute(string $attribute, $value) {} /** - * Sets up a behavior in a collection + * Cancel the current operation * - * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior + * @param bool $disableEvents + * @return bool */ - protected function addBehavior(\Phalcon\Mvc\Collection\BehaviorInterface $behavior) {} + protected function cancelOperation(bool $disableEvents): bool {} /** - * Skips the current operation forcing a success state + * Checks if the document exists in the collection * - * @param bool $skip + * @param MongoCollection $collection + * @return bool */ - public function skipOperation($skip) {} + protected function exists($collection): bool {} /** - * Returns the instance as an array representation + * Perform a count over a resultset * - * - * print_r( - * $robot->toArray() - * ); - * + * @param array $params + * @param Collection $collection + * @param \MongoDb $connection + * @return int + */ + protected static function getGroupResultset($params, Collection $collection, $connection): int {} + + /** + * Returns a collection resultset * + * @param array $params + * @param CollectionInterface $collection + * @param \MongoDb $connection + * @param bool $unique * @return array */ - public function toArray() {} + protected static function getResultset($params, CollectionInterface $collection, $connection, bool $unique) {} /** - * Serializes the object ignoring connections or protected properties + * Executes internal hooks before save a document * - * @return string + * @param \Phalcon\Di\DiInterface $container + * @param bool $disableEvents + * @param bool $exists + * @return bool */ - public function serialize() {} + final protected function preSave(\Phalcon\Di\DiInterface $container, bool $disableEvents, bool $exists): bool {} /** - * Unserializes the object from a serialized string + * Executes internal events after save a document * - * @param mixed $data + * @param bool $disableEvents + * @param bool $success + * @param bool $exists + * @return bool */ - public function unserialize($data) {} + final protected function postSave(bool $disableEvents, bool $success, bool $exists): bool {} + + /** + * Shared Code for CU Operations + * Prepares Collection + */ + protected function prepareCU() {} } diff --git a/src/Phalcon/mvc/CollectionInterface.php b/src/Phalcon/mvc/CollectionInterface.php index ab22a531..ead5cdd5 100644 --- a/src/Phalcon/mvc/CollectionInterface.php +++ b/src/Phalcon/mvc/CollectionInterface.php @@ -3,162 +3,163 @@ namespace Phalcon\Mvc; /** - * Phalcon\Mvc\CollectionInterface - * * Interface for Phalcon\Mvc\Collection */ interface CollectionInterface { /** - * Sets a value for the _id property, creates a MongoId object if needed + * Appends a customized message on the validation process * - * @param mixed $id + * @param \Phalcon\Messages\MessageInterface $message */ - public function setId($id); + public function appendMessage(\Phalcon\Messages\MessageInterface $message); /** - * Returns the value of the _id property + * Returns a cloned collection * - * @return MongoId + * @param CollectionInterface $collection + * @param array $document + * @return CollectionInterface */ - public function getId(); + public static function cloneResult(CollectionInterface $collection, array $document): CollectionInterface; /** - * Returns an array with reserved properties that cannot be part of the insert/update + * Perform a count over a collection * - * @return array + * @param array $parameters + * @return int */ - public function getReservedAttributes(); + public static function count(array $parameters = null): int; /** - * Returns collection name mapped in the model + * Deletes a model instance. Returning true on success or false otherwise * - * @return string + * @return bool */ - public function getSource(); + public function delete(): bool; /** - * Sets a service in the services container that returns the Mongo database + * Allows to query a set of records that match the specified conditions * - * @param string $connectionService + * @param array $parameters + * @return array */ - public function setConnectionService($connectionService); + public static function find(array $parameters = null): array; /** - * Retrieves a database connection + * Find a document by its id * - * @return MongoDb + * @param string $id + * @return null|CollectionInterface */ - public function getConnection(); + public static function findById($id): ?CollectionInterface; /** - * Sets the dirty state of the object using one of the DIRTY_STATE_ constants + * Allows to query the first record that match the specified conditions * - * @param int $dirtyState - * @return \Phalcon\Mvc\CollectionInterface + * @param array $parameters + * @return array */ - public function setDirtyState($dirtyState); + public static function findFirst(array $parameters = null): array; /** - * Returns one of the DIRTY_STATE_ constants telling if the record exists in the database or not + * Fires an event, implicitly calls behaviors and listeners in the events + * manager are notified * - * @return int + * @param string $eventName + * @return bool */ - public function getDirtyState(); + public function fireEvent(string $eventName): bool; /** - * Returns a cloned collection + * Fires an event, implicitly listeners in the events manager are notified + * This method stops if one of the callbacks/listeners returns bool false * - * @param CollectionInterface $collection - * @param array $document - * @return CollectionInterface + * @param string $eventName + * @return bool */ - public static function cloneResult(CollectionInterface $collection, array $document); + public function fireEventCancel(string $eventName): bool; /** - * Fires an event, implicitly calls behaviors and listeners in the events manager are notified + * Retrieves a database connection * - * @param string $eventName - * @return bool + * @return MongoDb */ - public function fireEvent($eventName); + public function getConnection(); /** - * Fires an event, implicitly listeners in the events manager are notified - * This method stops if one of the callbacks/listeners returns boolean false + * Returns one of the DIRTY_STATE_ constants telling if the record exists + * in the database or not * - * @param string $eventName - * @return bool + * @return int */ - public function fireEventCancel($eventName); + public function getDirtyState(): int; /** - * Check whether validation process has generated any messages + * Returns the value of the _id property * - * @return bool + * @return MongoId */ - public function validationHasFailed(); + public function getId(); /** * Returns all the validation messages * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return array|\Phalcon\Messages\MessageInterface[] */ - public function getMessages(); + public function getMessages(): array; /** - * Appends a customized message on the validation process + * Returns an array with reserved properties that cannot be part of the + * insert/update * - * @param \Phalcon\Mvc\Model\MessageInterface $message + * @return array */ - public function appendMessage(\Phalcon\Mvc\Model\MessageInterface $message); + public function getReservedAttributes(): array; /** - * Creates/Updates a collection based on the values in the attributes + * Returns collection name mapped in the model * - * @return bool + * @return string */ - public function save(); + public function getSource(): string; /** - * Find a document by its id + * Creates/Updates a collection based on the values in the attributes * - * @param string $id - * @return null|CollectionInterface + * @return bool */ - public static function findById($id); + public function save(): bool; /** - * Allows to query the first record that match the specified conditions + * Sets a service in the services container that returns the Mongo database * - * @param array $parameters - * @return array + * @param string $connectionService */ - public static function findFirst(array $parameters = null); + public function setConnectionService(string $connectionService); /** - * Allows to query a set of records that match the specified conditions + * Sets the dirty state of the object using one of the DIRTY_STATE_ + * constants * - * @param array $parameters - * @param $array parameters - * @return array + * @param int $dirtyState + * @return CollectionInterface */ - public static function find(array $parameters = null); + public function setDirtyState(int $dirtyState): CollectionInterface; /** - * Perform a count over a collection + * Sets a value for the _id property, creates a MongoId object if needed * - * @param array $parameters - * @return array + * @param mixed $id */ - public static function count(array $parameters = null); + public function setId($id); /** - * Deletes a model instance. Returning true on success or false otherwise + * Check whether validation process has generated any messages * * @return bool */ - public function delete(); + public function validationHasFailed(): bool; } diff --git a/src/Phalcon/mvc/Controller.php b/src/Phalcon/mvc/Controller.php index f4089c53..e7f03779 100644 --- a/src/Phalcon/mvc/Controller.php +++ b/src/Phalcon/mvc/Controller.php @@ -5,13 +5,15 @@ /** * Phalcon\Mvc\Controller * - * Every application controller should extend this class that encapsulates all the controller functionality + * Every application controller should extend this class that encapsulates all + * the controller functionality * - * The controllers provide the “flow” between models and views. Controllers are responsible - * for processing the incoming requests from the web browser, interrogating the models for data, - * and passing that data on to the views for presentation. + * The controllers provide the “flow” between models and views. Controllers are + * responsible for processing the incoming requests from the web browser, + * interrogating the models for data, and passing that data on to the views for + * presentation. * - * + * ```php * + * ``` */ abstract class Controller extends \Phalcon\Di\Injectable implements \Phalcon\Mvc\ControllerInterface { @@ -46,6 +48,6 @@ abstract class Controller extends \Phalcon\Di\Injectable implements \Phalcon\Mvc /** * Phalcon\Mvc\Controller constructor */ - public final function __construct() {} + final public function __construct() {} } diff --git a/src/Phalcon/mvc/Dispatcher.php b/src/Phalcon/mvc/Dispatcher.php index f48fc6ad..50644e36 100644 --- a/src/Phalcon/mvc/Dispatcher.php +++ b/src/Phalcon/mvc/Dispatcher.php @@ -3,13 +3,12 @@ namespace Phalcon\Mvc; /** - * Phalcon\Mvc\Dispatcher + * Dispatching is the process of taking the request object, extracting the + * module name, controller name, action name, and optional parameters contained + * in it, and then instantiating a controller and calling an action of that + * controller. * - * Dispatching is the process of taking the request object, extracting the module name, - * controller name, action name, and optional parameters contained in it, and then - * instantiating a controller and calling an action of that controller. - * - * + * ```php * $di = new \Phalcon\Di(); * * $dispatcher = new \Phalcon\Mvc\Dispatcher(); @@ -21,88 +20,24 @@ * $dispatcher->setParams([]); * * $controller = $dispatcher->dispatch(); - * + * ``` */ -class Dispatcher extends \Phalcon\Dispatcher implements \Phalcon\Mvc\DispatcherInterface +class Dispatcher extends \Phalcon\Dispatcher\AbstractDispatcher implements \Phalcon\Mvc\DispatcherInterface { - protected $_handlerSuffix = 'Controller'; - - - protected $_defaultHandler = 'index'; - - - protected $_defaultAction = 'index'; - - - /** - * Sets the default controller suffix - * - * @param string $controllerSuffix - */ - public function setControllerSuffix($controllerSuffix) {} - - /** - * Sets the default controller name - * - * @param string $controllerName - */ - public function setDefaultController($controllerName) {} - - /** - * Sets the controller name to be dispatched - * - * @param string $controllerName - */ - public function setControllerName($controllerName) {} - - /** - * Gets last dispatched controller name - * - * @return string - */ - public function getControllerName() {} + protected $defaultAction = 'index'; - /** - * Gets previous dispatched namespace name - * - * @return string - */ - public function getPreviousNamespaceName() {} - /** - * Gets previous dispatched controller name - * - * @return string - */ - public function getPreviousControllerName() {} + protected $defaultHandler = 'index'; - /** - * Gets previous dispatched action name - * - * @return string - */ - public function getPreviousActionName() {} - /** - * Throws an internal exception - * - * @param string $message - * @param int $exceptionCode - */ - protected function _throwDispatchException($message, $exceptionCode = 0) {} + protected $handlerSuffix = 'Controller'; - /** - * Handles a user exception - * - * @param \Exception $exception - */ - protected function _handleException(\Exception $exception) {} /** * Forwards the execution flow to another controller/action. * - * + * ```php * use Phalcon\Events\Event; * use Phalcon\Mvc\Dispatcher; * use App\Backend\Bootstrap as Backend; @@ -136,8 +71,13 @@ protected function _handleException(\Exception $exception) {} * function(Event $event, Dispatcher $dispatcher, array $forward) use ($modules) { * $metadata = $modules[$forward["module"]]["metadata"]; * - * $dispatcher->setModuleName($forward["module"]); - * $dispatcher->setNamespaceName($metadata["controllersNamespace"]); + * $dispatcher->setModuleName( + * $forward["module"] + * ); + * + * $dispatcher->setNamespaceName( + * $metadata["controllersNamespace"] + * ); * } * ); * @@ -149,31 +89,96 @@ protected function _handleException(\Exception $exception) {} * "action" => "index", * ] * ); - * + * ``` * * @param array $forward */ public function forward($forward) {} /** - * Possible controller class name that will be located to dispatch the request + * Returns the active controller in the dispatcher + * + * @return \Phalcon\Mvc\ControllerInterface + */ + public function getActiveController(): ControllerInterface {} + + /** + * Possible controller class name that will be located to dispatch the + * request * * @return string */ - public function getControllerClass() {} + public function getControllerClass(): string {} + + /** + * Gets last dispatched controller name + * + * @return string + */ + public function getControllerName(): string {} /** * Returns the latest dispatched controller * * @return \Phalcon\Mvc\ControllerInterface */ - public function getLastController() {} + public function getLastController(): ControllerInterface {} /** - * Returns the active controller in the dispatcher + * Gets previous dispatched action name * - * @return \Phalcon\Mvc\ControllerInterface + * @return string + */ + public function getPreviousActionName(): string {} + + /** + * Gets previous dispatched controller name + * + * @return string + */ + public function getPreviousControllerName(): string {} + + /** + * Gets previous dispatched namespace name + * + * @return string + */ + public function getPreviousNamespaceName(): string {} + + /** + * Sets the controller name to be dispatched + * + * @param string $controllerName + */ + public function setControllerName(string $controllerName) {} + + /** + * Sets the default controller suffix + * + * @param string $controllerSuffix + */ + public function setControllerSuffix(string $controllerSuffix) {} + + /** + * Sets the default controller name + * + * @param string $controllerName + */ + public function setDefaultController(string $controllerName) {} + + /** + * Handles a user exception + * + * @param \Exception $exception + */ + protected function handleException(\Exception $exception) {} + + /** + * Throws an internal exception + * + * @param string $message + * @param int $exceptionCode */ - public function getActiveController() {} + protected function throwDispatchException(string $message, int $exceptionCode = 0) {} } diff --git a/src/Phalcon/mvc/DispatcherInterface.php b/src/Phalcon/mvc/DispatcherInterface.php index d0625078..3019e142 100644 --- a/src/Phalcon/mvc/DispatcherInterface.php +++ b/src/Phalcon/mvc/DispatcherInterface.php @@ -7,49 +7,49 @@ * * Interface for Phalcon\Mvc\Dispatcher */ -interface DispatcherInterface extends \Phalcon\DispatcherInterface +interface DispatcherInterface extends \Phalcon\Dispatcher\DispatcherInterface { /** - * Sets the default controller suffix + * Returns the active controller in the dispatcher * - * @param string $controllerSuffix + * @return \Phalcon\Mvc\ControllerInterface */ - public function setControllerSuffix($controllerSuffix); + public function getActiveController(): ControllerInterface; /** - * Sets the default controller name + * Gets last dispatched controller name * - * @param string $controllerName + * @return string */ - public function setDefaultController($controllerName); + public function getControllerName(): string; /** - * Sets the controller name to be dispatched + * Returns the latest dispatched controller * - * @param string $controllerName + * @return \Phalcon\Mvc\ControllerInterface */ - public function setControllerName($controllerName); + public function getLastController(): ControllerInterface; /** - * Gets last dispatched controller name + * Sets the default controller suffix * - * @return string + * @param string $controllerSuffix */ - public function getControllerName(); + public function setControllerSuffix(string $controllerSuffix); /** - * Returns the latest dispatched controller + * Sets the controller name to be dispatched * - * @return \Phalcon\Mvc\ControllerInterface + * @param string $controllerName */ - public function getLastController(); + public function setControllerName(string $controllerName); /** - * Returns the active controller in the dispatcher + * Sets the default controller name * - * @return \Phalcon\Mvc\ControllerInterface + * @param string $controllerName */ - public function getActiveController(); + public function setDefaultController(string $controllerName); } diff --git a/src/Phalcon/mvc/EntityInterface.php b/src/Phalcon/mvc/EntityInterface.php index 196e0b86..ccff1790 100644 --- a/src/Phalcon/mvc/EntityInterface.php +++ b/src/Phalcon/mvc/EntityInterface.php @@ -14,9 +14,9 @@ interface EntityInterface * Reads an attribute value by its name * * @param string $attribute - * @return mixed + * @return mixed|null */ - public function readAttribute($attribute); + public function readAttribute(string $attribute): ?; /** * Writes an attribute value by its name @@ -24,6 +24,6 @@ public function readAttribute($attribute); * @param string $attribute * @param mixed $value */ - public function writeAttribute($attribute, $value); + public function writeAttribute(string $attribute, $value); } diff --git a/src/Phalcon/mvc/Micro.php b/src/Phalcon/mvc/Micro.php index 7f8ca591..b1fba1ac 100644 --- a/src/Phalcon/mvc/Micro.php +++ b/src/Phalcon/mvc/Micro.php @@ -5,11 +5,12 @@ /** * Phalcon\Mvc\Micro * - * With Phalcon you can create "Micro-Framework like" applications. By doing this, you only need to - * write a minimal amount of code to create a PHP application. Micro applications are suitable - * to small applications, APIs and prototypes in a practical way. + * With Phalcon you can create "Micro-Framework like" applications. By doing + * this, you only need to write a minimal amount of code to create a PHP + * application. Micro applications are suitable to small applications, APIs and + * prototypes in a practical way. * - * + * ```php * $app = new \Phalcon\Mvc\Micro(); * * $app->get( @@ -19,185 +20,161 @@ * } * ); * - * $app->handle(); - * + * $app->handle("/say/welcome/Phalcon"); + * ``` */ class Micro extends \Phalcon\Di\Injectable implements \ArrayAccess { - protected $_dependencyInjector; + protected $activeHandler; - protected $_handlers = array(); + protected $afterBindingHandlers = array(); - protected $_router; + protected $afterHandlers = array(); - protected $_stopped; + protected $beforeHandlers = array(); - protected $_notFoundHandler; + protected $container; - protected $_errorHandler; + protected $errorHandler; - protected $_activeHandler; + protected $finishHandlers = array(); - protected $_beforeHandlers; + protected $handlers = array(); - protected $_afterHandlers; + protected $modelBinder; - protected $_finishHandlers; + protected $notFoundHandler; - protected $_returnedValue; + protected $responseHandler; - protected $_modelBinder; + protected $returnedValue; - protected $_afterBindingHandlers; + protected $router; - /** - * Phalcon\Mvc\Micro constructor - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function __construct(\Phalcon\DiInterface $dependencyInjector = null) {} + protected $stopped; - /** - * Sets the DependencyInjector container - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} /** - * Maps a route to a handler without any HTTP method constraint + * Phalcon\Mvc\Micro constructor * - * @param string $routePattern - * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @param \Phalcon\Di\DiInterface $container */ - public function map($routePattern, $handler) {} + public function __construct(\Phalcon\Di\DiInterface $container = null) {} /** - * Maps a route to a handler that only matches if the HTTP method is GET + * Appends an 'after' middleware to be called after execute the route * - * @param string $routePattern * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @return Micro */ - public function get($routePattern, $handler) {} + public function after($handler): Micro {} /** - * Maps a route to a handler that only matches if the HTTP method is POST + * Appends a afterBinding middleware to be called after model binding * - * @param string $routePattern * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @return Micro */ - public function post($routePattern, $handler) {} + public function afterBinding($handler): Micro {} /** - * Maps a route to a handler that only matches if the HTTP method is PUT + * Appends a before middleware to be called before execute the route * - * @param string $routePattern * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @return Micro */ - public function put($routePattern, $handler) {} + public function before($handler): Micro {} /** - * Maps a route to a handler that only matches if the HTTP method is PATCH + * Maps a route to a handler that only matches if the HTTP method is DELETE * * @param string $routePattern * @param callable $handler * @return \Phalcon\Mvc\Router\RouteInterface */ - public function patch($routePattern, $handler) {} + public function delete(string $routePattern, $handler): RouteInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is HEAD + * Sets a handler that will be called when an exception is thrown handling + * the route * - * @param string $routePattern * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @return Micro */ - public function head($routePattern, $handler) {} + public function error($handler): Micro {} /** - * Maps a route to a handler that only matches if the HTTP method is DELETE + * Appends a 'finish' middleware to be called when the request is finished * - * @param string $routePattern * @param callable $handler - * @return \Phalcon\Mvc\Router\RouteInterface + * @return Micro */ - public function delete($routePattern, $handler) {} + public function finish($handler): Micro {} /** - * Maps a route to a handler that only matches if the HTTP method is OPTIONS + * Maps a route to a handler that only matches if the HTTP method is GET * * @param string $routePattern * @param callable $handler * @return \Phalcon\Mvc\Router\RouteInterface */ - public function options($routePattern, $handler) {} + public function get(string $routePattern, $handler): RouteInterface {} /** - * Mounts a collection of handlers + * Return the handler that will be called for the matched route * - * @param \Phalcon\Mvc\Micro\CollectionInterface $collection - * @return Micro + * @return callable */ - public function mount(\Phalcon\Mvc\Micro\CollectionInterface $collection) {} + public function getActiveHandler() {} /** - * Sets a handler that will be called when the router doesn't match any of the defined routes + * Returns bound models from binder instance * - * @param callable $handler - * @return Micro + * @return array */ - public function notFound($handler) {} + public function getBoundModels(): array {} /** - * Sets a handler that will be called when an exception is thrown handling the route + * Returns the internal handlers attached to the application * - * @param callable $handler - * @return Micro + * @return array */ - public function error($handler) {} + public function getHandlers(): array {} /** - * Returns the internal router used by the application + * Gets model binder * - * @return RouterInterface + * @return null|\Phalcon\Mvc\Model\BinderInterface */ - public function getRouter() {} + public function getModelBinder(): ?BinderInterface {} /** - * Sets a service from the DI + * Returns the value returned by the executed handler * - * @param string $serviceName - * @param mixed $definition - * @param boolean $shared - * @return \Phalcon\Di\ServiceInterface + * @return mixed */ - public function setService($serviceName, $definition, $shared = false) {} + public function getReturnedValue() {} /** - * Checks if a service is registered in the DI + * Returns the internal router used by the application * - * @param string $serviceName - * @return bool + * @return RouterInterface */ - public function hasService($serviceName) {} + public function getRouter(): RouterInterface {} /** * Obtains a service from the DI @@ -205,7 +182,7 @@ public function hasService($serviceName) {} * @param string $serviceName * @return object */ - public function getService($serviceName) {} + public function getService(string $serviceName) {} /** * Obtains a shared service from the DI @@ -213,7 +190,7 @@ public function getService($serviceName) {} * @param string $serviceName * @return mixed */ - public function getSharedService($serviceName) {} + public function getSharedService(string $serviceName) {} /** * Handle the whole request @@ -221,140 +198,187 @@ public function getSharedService($serviceName) {} * @param string $uri * @return mixed */ - public function handle($uri = null) {} + public function handle(string $uri) {} /** - * Stops the middleware execution avoiding than other middlewares be executed + * Checks if a service is registered in the DI + * + * @param string $serviceName + * @return bool */ - public function stop() {} + public function hasService(string $serviceName): bool {} /** - * Sets externally the handler that must be called by the matched route + * Maps a route to a handler that only matches if the HTTP method is HEAD * - * @param callable $activeHandler + * @param string $routePattern + * @param callable $handler + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setActiveHandler($activeHandler) {} + public function head(string $routePattern, $handler): RouteInterface {} /** - * Return the handler that will be called for the matched route + * Maps a route to a handler without any HTTP method constraint * - * @return callable + * @param string $routePattern + * @param callable $handler + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getActiveHandler() {} + public function map(string $routePattern, $handler): RouteInterface {} /** - * Returns the value returned by the executed handler + * Mounts a collection of handlers * - * @return mixed + * @param \Phalcon\Mvc\Micro\CollectionInterface $collection + * @return Micro */ - public function getReturnedValue() {} + public function mount(\Phalcon\Mvc\Micro\CollectionInterface $collection): Micro {} /** - * Check if a service is registered in the internal services container using the array syntax + * Sets a handler that will be called when the router doesn't match any of + * the defined routes * - * @param string $alias - * @return bool + * @param callable $handler + * @return Micro */ - public function offsetExists($alias) {} + public function notFound($handler): Micro {} /** - * Allows to register a shared service in the internal services container using the array syntax - * - * - * $app["request"] = new \Phalcon\Http\Request(); - * + * Check if a service is registered in the internal services container using + * the array syntax * - * @param string $alias - * @param mixed $definition + * @param mixed $alias + * @return bool */ - public function offsetSet($alias, $definition) {} + public function offsetExists($alias): bool {} /** - * Allows to obtain a shared service in the internal services container using the array syntax + * Allows to obtain a shared service in the internal services container + * using the array syntax * - * + * ```php * var_dump( * $app["request"] * ); - * + * ``` * - * @param string $alias + * @param mixed $alias * @return mixed */ public function offsetGet($alias) {} /** - * Removes a service from the internal services container using the array syntax + * Allows to register a shared service in the internal services container + * using the array syntax * - * @param string $alias + * ```php + * $app["request"] = new \Phalcon\Http\Request(); + * ``` + * + * @param mixed $alias + * @param mixed $definition + */ + public function offsetSet($alias, $definition) {} + + /** + * Removes a service from the internal services container using the array + * syntax + * + * @param mixed $alias */ public function offsetUnset($alias) {} /** - * Appends a before middleware to be called before execute the route + * Maps a route to a handler that only matches if the HTTP method is OPTIONS * + * @param string $routePattern * @param callable $handler - * @return Micro + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function before($handler) {} + public function options(string $routePattern, $handler): RouteInterface {} /** - * Appends a afterBinding middleware to be called after model binding + * Maps a route to a handler that only matches if the HTTP method is PATCH * + * @param string $routePattern * @param callable $handler - * @return Micro + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function afterBinding($handler) {} + public function patch(string $routePattern, $handler): RouteInterface {} /** - * Appends an 'after' middleware to be called after execute the route + * Maps a route to a handler that only matches if the HTTP method is POST * + * @param string $routePattern * @param callable $handler - * @return Micro + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function after($handler) {} + public function post(string $routePattern, $handler): RouteInterface {} /** - * Appends a 'finish' middleware to be called when the request is finished + * Maps a route to a handler that only matches if the HTTP method is PUT * + * @param string $routePattern * @param callable $handler - * @return Micro + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function finish($handler) {} + public function put(string $routePattern, $handler): RouteInterface {} /** - * Returns the internal handlers attached to the application + * Sets externally the handler that must be called by the matched route * - * @return array + * @param callable $activeHandler */ - public function getHandlers() {} + public function setActiveHandler($activeHandler) {} /** - * Gets model binder + * Sets the DependencyInjector container * - * @return null|\Phalcon\Mvc\Model\BinderInterface + * @param \Phalcon\Di\DiInterface $container */ - public function getModelBinder() {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** * Sets model binder * - * + * ```php * $micro = new Micro($di); - * $micro->setModelBinder(new Binder(), 'cache'); - * + * + * $micro->setModelBinder( + * new Binder(), + * 'cache' + * ); + * ``` * * @param \Phalcon\Mvc\Model\BinderInterface $modelBinder * @param mixed $cache * @return Micro */ - public function setModelBinder(\Phalcon\Mvc\Model\BinderInterface $modelBinder, $cache = null) {} + public function setModelBinder(\Phalcon\Mvc\Model\BinderInterface $modelBinder, $cache = null): Micro {} /** - * Returns bound models from binder instance + * Appends a custom 'reponse' handler to be called insted of the default + * response handler * - * @return array + * @param callable $handler + * @return Micro */ - public function getBoundModels() {} + public function setResponseHandler($handler): Micro {} + + /** + * Sets a service from the DI + * + * @param string $serviceName + * @param mixed $definition + * @param bool $shared + * @return \Phalcon\Di\ServiceInterface + */ + public function setService(string $serviceName, $definition, bool $shared = false): ServiceInterface {} + + /** + * Stops the middleware execution avoiding than other middlewares be + * executed + */ + public function stop() {} } diff --git a/src/Phalcon/mvc/Model.php b/src/Phalcon/mvc/Model.php index 85fada49..4778080b 100644 --- a/src/Phalcon/mvc/Model.php +++ b/src/Phalcon/mvc/Model.php @@ -5,19 +5,21 @@ /** * Phalcon\Mvc\Model * - * Phalcon\Mvc\Model connects business objects and database tables to create - * a persistable domain model where logic and data are presented in one wrapping. + * Phalcon\Mvc\Model connects business objects and database tables to create a + * persistable domain model where logic and data are presented in one wrapping. * It‘s an implementation of the object-relational mapping (ORM). * - * A model represents the information (data) of the application and the rules to manipulate that data. - * Models are primarily used for managing the rules of interaction with a corresponding database table. - * In most cases, each table in your database will correspond to one model in your application. - * The bulk of your application's business logic will be concentrated in the models. + * A model represents the information (data) of the application and the rules to + * manipulate that data. Models are primarily used for managing the rules of + * interaction with a corresponding database table. In most cases, each table in + * your database will correspond to one model in your application. The bulk of + * your application's business logic will be concentrated in the models. * - * Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, giving to developers high performance - * when interacting with databases while is also easy to use. + * Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, + * giving to developers high performance when interacting with databases while + * is also easy to use. * - * + * ```php * $robot = new Robots(); * * $robot->type = "mechanical"; @@ -35,75 +37,78 @@ * } else { * echo "Great, a new robot was saved successfully!"; * } - * + * ``` */ abstract class Model implements \Phalcon\Mvc\EntityInterface, \Phalcon\Mvc\ModelInterface, \Phalcon\Mvc\Model\ResultInterface, \Phalcon\Di\InjectionAwareInterface, \Serializable, \JsonSerializable { - const TRANSACTION_INDEX = 'transaction'; + const DIRTY_STATE_DETACHED = 2; - const OP_NONE = 0; + const DIRTY_STATE_PERSISTENT = 0; - const OP_CREATE = 1; + const DIRTY_STATE_TRANSIENT = 1; - const OP_UPDATE = 2; + const OP_CREATE = 1; const OP_DELETE = 3; - const DIRTY_STATE_PERSISTENT = 0; + const OP_NONE = 0; - const DIRTY_STATE_TRANSIENT = 1; + const OP_UPDATE = 2; - const DIRTY_STATE_DETACHED = 2; + const TRANSACTION_INDEX = 'transaction'; + + + protected $container; - protected $_dependencyInjector; + protected $dirtyState = 1; - protected $_modelsManager; + protected $dirtyRelated = array(); - protected $_modelsMetaData; + protected $errorMessages = array(); - protected $_errorMessages; + protected $modelsManager; - protected $_operationMade = 0; + protected $modelsMetaData; - protected $_dirtyState = 1; + protected $related = array(); - protected $_transaction; + protected $operationMade = 0; - protected $_uniqueKey; + protected $oldSnapshot = array(); - protected $_uniqueParams; + protected $skipped; - protected $_uniqueTypes; + protected $snapshot; - protected $_skipped; + protected $transaction; - protected $_related; + protected $uniqueKey; - protected $_snapshot; + protected $uniqueParams; - protected $_oldSnapshot; + protected $uniqueTypes; @@ -113,198 +118,114 @@ public function getTransaction() {} * Phalcon\Mvc\Model constructor * * @param mixed $data - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @param \Phalcon\Mvc\Model\ManagerInterface $modelsManager */ - public final function __construct($data = null, \Phalcon\DiInterface $dependencyInjector = null, \Phalcon\Mvc\Model\ManagerInterface $modelsManager = null) {} + final public function __construct($data = null, \Phalcon\Di\DiInterface $container = null, \Phalcon\Mvc\Model\ManagerInterface $modelsManager = null) {} /** - * Sets the dependency injection container - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the dependency injection container + * Handles method calls when a method is not implemented * - * @return \Phalcon\DiInterface + * @param string $method + * @param array $arguments + * @return mixed */ - public function getDI() {} + public function __call(string $method, array $arguments) {} /** - * Sets a custom events manager + * Handles method calls when a static method is not implemented * - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @param string $method + * @param array $arguments + * @return mixed */ - protected function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + public static function __callStatic(string $method, array $arguments) {} /** - * Returns the custom events manager + * Magic method to get related records using the relation alias as a + * property * - * @return \Phalcon\Events\ManagerInterface + * @param string $property + * @return mixed */ - protected function getEventsManager() {} + public function __get(string $property) {} /** - * Returns the models meta-data service related to the entity instance + * Magic method to check if a property is a valid relation * - * @return \Phalcon\Mvc\Model\MetaDataInterface + * @param string $property + * @return bool */ - public function getModelsMetaData() {} + public function __isset(string $property): bool {} /** - * Returns the models manager related to the entity instance + * Magic method to assign values to the the model * - * @return \Phalcon\Mvc\Model\ManagerInterface + * @param string $property + * @param mixed $value */ - public function getModelsManager() {} + public function __set(string $property, $value) {} /** - * Sets a transaction related to the Model instance - * - * - * use Phalcon\Mvc\Model\Transaction\Manager as TxManager; - * use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - * - * try { - * $txManager = new TxManager(); - * - * $transaction = $txManager->get(); - * - * $robot = new Robots(); - * - * $robot->setTransaction($transaction); - * - * $robot->name = "WALL·E"; - * $robot->created_at = date("Y-m-d"); - * - * if ($robot->save() === false) { - * $transaction->rollback("Can't save robot"); - * } - * - * $robotPart = new RobotParts(); - * - * $robotPart->setTransaction($transaction); + * Setups a behavior in a model * - * $robotPart->type = "head"; + * ```php + * use Phalcon\Mvc\Model; + * use Phalcon\Mvc\Model\Behavior\Timestampable; * - * if ($robotPart->save() === false) { - * $transaction->rollback("Robot part cannot be saved"); + * class Robots extends Model + * { + * public function initialize() + * { + * $this->addBehavior( + * new Timestampable( + * [ + * "onCreate" => [ + * "field" => "created_at", + * "format" => "Y-m-d", + * ], + * ] + * ) + * ); * } - * - * $transaction->commit(); - * } catch (TxFailed $e) { - * echo "Failed, reason: ", $e->getMessage(); * } - * - * - * @param \Phalcon\Mvc\Model\TransactionInterface $transaction - * @return ModelInterface - */ - public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} - - /** - * Sets the table name to which model should be mapped - * - * @param string $source - * @return Model - */ - protected function setSource($source) {} - - /** - * Returns the table name mapped in the model - * - * @return string - */ - public function getSource() {} - - /** - * Sets schema name where the mapped table is located - * - * @param string $schema - * @return Model - */ - protected function setSchema($schema) {} - - /** - * Returns schema name where the mapped table is located - * - * @return string - */ - public function getSchema() {} - - /** - * Sets the DependencyInjection connection service name - * - * @param string $connectionService - * @return Model - */ - public function setConnectionService($connectionService) {} - - /** - * Sets the DependencyInjection connection service name used to read data + * ``` * - * @param string $connectionService - * @return Model - */ - public function setReadConnectionService($connectionService) {} - - /** - * Sets the DependencyInjection connection service name used to write data - * - * @param string $connectionService - * @return Model - */ - public function setWriteConnectionService($connectionService) {} - - /** - * Returns the DependencyInjection connection service name used to read data related the model - * - * @return string - */ - public function getReadConnectionService() {} - - /** - * Returns the DependencyInjection connection service name used to write data related to the model - * - * @return string + * @param \Phalcon\Mvc\Model\BehaviorInterface $behavior */ - public function getWriteConnectionService() {} + public function addBehavior(\Phalcon\Mvc\Model\BehaviorInterface $behavior) {} /** - * Sets the dirty state of the object using one of the DIRTY_STATE_ constants + * Appends a customized message on the validation process * - * @param int $dirtyState - * @return ModelInterface - */ - public function setDirtyState($dirtyState) {} - - /** - * Returns one of the DIRTY_STATE_ constants telling if the record exists in the database or not + * ```php + * use Phalcon\Mvc\Model; + * use Phalcon\Messages\Message as Message; * - * @return int - */ - public function getDirtyState() {} - - /** - * Gets the connection used to read data for the model + * class Robots extends Model + * { + * public function beforeSave() + * { + * if ($this->name === "Peter") { + * $message = new Message( + * "Sorry, but a robot cannot be named Peter" + * ); * - * @return \Phalcon\Db\AdapterInterface - */ - public function getReadConnection() {} - - /** - * Gets the connection used to write data to the model + * $this->appendMessage($message); + * } + * } + * } + * ``` * - * @return \Phalcon\Db\AdapterInterface + * @param \Phalcon\Messages\MessageInterface $message + * @return \Phalcon\Mvc\ModelInterface */ - public function getWriteConnection() {} + public function appendMessage(\Phalcon\Messages\MessageInterface $message): ModelInterface {} /** * Assigns values to a model from an array * - * + * ```php * $robot->assign( * [ * "type" => "mechanical", @@ -345,20 +266,50 @@ public function getWriteConnection() {} * "year", * ] * ); - * + * ``` * * @param array $data * @param array $dataColumnMap array to transform keys of data to another * @param array $whiteList - * @return Model + * @return \Phalcon\Mvc\ModelInterface */ - public function assign(array $data, $dataColumnMap = null, $whiteList = null) {} + public function assign(array $data, $dataColumnMap = null, $whiteList = null): ModelInterface {} /** - * Assigns values to a model from an array, returning a new model. + * Returns the average value on a column for a result-set of rows matching + * the specified conditions * - * - * $robot = \Phalcon\Mvc\Model::cloneResultMap( + * ```php + * // What's the average price of robots? + * $average = Robots::average( + * [ + * "column" => "price", + * ] + * ); + * + * echo "The average price is ", $average, "\n"; + * + * // What's the average price of mechanical robots? + * $average = Robots::average( + * [ + * "type = 'mechanical'", + * "column" => "price", + * ] + * ); + * + * echo "The average price of mechanical robots is ", $average, "\n"; + * ``` + * + * @param array $parameters + * @return double + */ + public static function average($parameters = null): float {} + + /** + * Assigns values to a model from an array returning a new model + * + * ```php + * $robot = Phalcon\Mvc\Model::cloneResult( * new Robots(), * [ * "type" => "mechanical", @@ -366,32 +317,20 @@ public function assign(array $data, $dataColumnMap = null, $whiteList = null) {} * "year" => 1952, * ] * ); - * + * ``` * - * @param \Phalcon\Mvc\ModelInterface|\Phalcon\Mvc\Model\Row $base + * @param \Phalcon\Mvc\ModelInterface $base * @param array $data - * @param array $columnMap * @param int $dirtyState - * @param boolean $keepSnapshots - * @return Model - */ - public static function cloneResultMap($base, array $data, $columnMap, $dirtyState = 0, $keepSnapshots = null) {} - - /** - * Returns an hydrated result based on the data and the column map - * - * @param array $data - * @param array $columnMap - * @param int $hydrationMode - * @return mixed + * @return \Phalcon\Mvc\ModelInterface */ - public static function cloneResultMapHydrate(array $data, $columnMap, $hydrationMode) {} + public static function cloneResult(\Phalcon\Mvc\ModelInterface $base, array $data, int $dirtyState = 0): ModelInterface {} /** - * Assigns values to a model from an array returning a new model + * Assigns values to a model from an array, returning a new model. * - * - * $robot = Phalcon\Mvc\Model::cloneResult( + * ```php + * $robot = \Phalcon\Mvc\Model::cloneResultMap( * new Robots(), * [ * "type" => "mechanical", @@ -399,41 +338,139 @@ public static function cloneResultMapHydrate(array $data, $columnMap, $hydration * "year" => 1952, * ] * ); - * + * ``` * - * @param \Phalcon\Mvc\ModelInterface $base + * @param \Phalcon\Mvc\ModelInterface|\Phalcon\Mvc\Model\Row $base * @param array $data + * @param array $columnMap * @param int $dirtyState + * @param bool $keepSnapshots * @return \Phalcon\Mvc\ModelInterface */ - public static function cloneResult(ModelInterface $base, array $data, $dirtyState = 0) {} + public static function cloneResultMap($base, array $data, $columnMap, int $dirtyState = 0, bool $keepSnapshots = null): ModelInterface {} /** - * Query for a set of records that match the specified conditions + * Returns an hydrated result based on the data and the column map + * + * @param array $data + * @param array $columnMap + * @param int $hydrationMode + * @return mixed + */ + public static function cloneResultMapHydrate(array $data, $columnMap, int $hydrationMode) {} + + /** + * Counts how many records match the specified conditions * - * + * ```php * // How many robots are there? - * $robots = Robots::find(); + * $number = Robots::count(); * - * echo "There are ", count($robots), "\n"; + * echo "There are ", $number, "\n"; * * // How many mechanical robots are there? - * $robots = Robots::find( - * "type = 'mechanical'" - * ); - * - * echo "There are ", count($robots), "\n"; + * $number = Robots::count("type = 'mechanical'"); * - * // Get and print virtual robots ordered by name - * $robots = Robots::find( - * [ - * "type = 'virtual'", - * "order" => "name", - * ] - * ); + * echo "There are ", $number, " mechanical robots\n"; + * ``` * - * foreach ($robots as $robot) { - * echo $robot->name, "\n"; + * @param array $parameters + * @return int + */ + public static function count($parameters = null): int {} + + /** + * Inserts a model instance. If the instance already exists in the + * persistence it will throw an exception + * Returning true on success or false otherwise. + * + * ```php + * // Creating a new robot + * $robot = new Robots(); + * + * $robot->type = "mechanical"; + * $robot->name = "Astro Boy"; + * $robot->year = 1952; + * + * $robot->create(); + * + * // Passing an array to create + * $robot = new Robots(); + * + * $robot->assign( + * [ + * "type" => "mechanical", + * "name" => "Astro Boy", + * "year" => 1952, + * ] + * ); + * + * $robot->create(); + * ``` + * + * @return bool + */ + public function create(): bool {} + + /** + * Deletes a model instance. Returning true on success or false otherwise. + * + * ```php + * $robot = Robots::findFirst("id=100"); + * + * $robot->delete(); + * + * $robots = Robots::find("type = 'mechanical'"); + * + * foreach ($robots as $robot) { + * $robot->delete(); + * } + * ``` + * + * @return bool + */ + public function delete(): bool {} + + /** + * Returns a simple representation of the object that can be used with + * `var_dump()` + * + * ```php + * var_dump( + * $robot->dump() + * ); + * ``` + * + * @return array + */ + public function dump(): array {} + + /** + * Query for a set of records that match the specified conditions + * + * ```php + * // How many robots are there? + * $robots = Robots::find(); + * + * echo "There are ", count($robots), "\n"; + * + * // How many mechanical robots are there? + * $robots = Robots::find( + * "type = 'mechanical'" + * ); + * + * echo "There are ", count($robots), "\n"; + * + * // Get and print virtual robots ordered by name + * $robots = Robots::find( + * [ + * "type = 'virtual'", + * "order" => "name", + * ] + * ); + * + * foreach ($robots as $robot) { + * echo $robot->name, "\n"; * } * * // Get first 100 virtual robots ordered by name @@ -446,7 +483,7 @@ public static function cloneResult(ModelInterface $base, array $data, $dirtyStat * ); * * foreach ($robots as $robot) { - * echo $robot->name, "\n"; + * echo $robot->name, "\n"; * } * * // encapsulate find it into an running transaction esp. useful for application unit-tests @@ -454,11 +491,27 @@ public static function cloneResult(ModelInterface $base, array $data, $dirtyStat * * $myTransaction = new Transaction(\Phalcon\Di::getDefault()); * $myTransaction->begin(); + * * $newRobot = new Robot(); * $newRobot->setTransaction($myTransaction); - * $newRobot->save(['name' => 'test', 'type' => 'mechanical', 'year' => 1944]); * - * $resultInsideTransaction = Robot::find(['name' => 'test', Model::TRANSACTION_INDEX => $myTransaction]); + * $newRobot->assign( + * [ + * 'name' => 'test', + * 'type' => 'mechanical', + * 'year' => 1944, + * ] + * ); + * + * $newRobot->save(); + * + * $resultInsideTransaction = Robot::find( + * [ + * 'name' => 'test', + * Model::TRANSACTION_INDEX => $myTransaction, + * ] + * ); + * * $resultOutsideTransaction = Robot::find(['name' => 'test']); * * foreach ($setInsideTransaction as $robot) { @@ -481,39 +534,85 @@ public static function cloneResult(ModelInterface $base, array $data, $dirtyStat * // add a new robots * $firstNewRobot = new Robot(); * $firstNewRobot->setTransaction($myTransaction1); - * $firstNewRobot->save(['name' => 'first-transaction-robot', 'type' => 'mechanical', 'year' => 1944]); + * $firstNewRobot->assign( + * [ + * 'name' => 'first-transaction-robot', + * 'type' => 'mechanical', + * 'year' => 1944, + * ] + * ); + * $firstNewRobot->save(); * * $secondNewRobot = new Robot(); * $secondNewRobot->setTransaction($myTransaction2); - * $secondNewRobot->save(['name' => 'second-transaction-robot', 'type' => 'fictional', 'year' => 1984]); + * $secondNewRobot->assign( + * [ + * 'name' => 'second-transaction-robot', + * 'type' => 'fictional', + * 'year' => 1984, + * ] + * ); + * $secondNewRobot->save(); * * // this transaction will find the robot. - * $resultInFirstTransaction = Robot::find(['name' => 'first-transaction-robot', Model::TRANSACTION_INDEX => $myTransaction1]); + * $resultInFirstTransaction = Robot::find( + * [ + * 'name' => 'first-transaction-robot', + * Model::TRANSACTION_INDEX => $myTransaction1, + * ] + * ); + * * // this transaction won't find the robot. - * $resultInSecondTransaction = Robot::find(['name' => 'first-transaction-robot', Model::TRANSACTION_INDEX => $myTransaction2]); + * $resultInSecondTransaction = Robot::find( + * [ + * 'name' => 'first-transaction-robot', + * Model::TRANSACTION_INDEX => $myTransaction2, + * ] + * ); + * * // this transaction won't find the robot. - * $resultOutsideAnyExplicitTransaction = Robot::find(['name' => 'first-transaction-robot']); + * $resultOutsideAnyExplicitTransaction = Robot::find( + * [ + * 'name' => 'first-transaction-robot', + * ] + * ); * * // this transaction won't find the robot. - * $resultInFirstTransaction = Robot::find(['name' => 'second-transaction-robot', Model::TRANSACTION_INDEX => $myTransaction2]); + * $resultInFirstTransaction = Robot::find( + * [ + * 'name' => 'second-transaction-robot', + * Model::TRANSACTION_INDEX => $myTransaction2, + * ] + * ); + * * // this transaction will find the robot. - * $resultInSecondTransaction = Robot::find(['name' => 'second-transaction-robot', Model::TRANSACTION_INDEX => $myTransaction1]); + * $resultInSecondTransaction = Robot::find( + * [ + * 'name' => 'second-transaction-robot', + * Model::TRANSACTION_INDEX => $myTransaction1, + * ] + * ); + * * // this transaction won't find the robot. - * $resultOutsideAnyExplicitTransaction = Robot::find(['name' => 'second-transaction-robot']); + * $resultOutsideAnyExplicitTransaction = Robot::find( + * [ + * 'name' => 'second-transaction-robot', + * ] + * ); * * $transaction1->rollback(); * $transaction2->rollback(); - * + * ``` * * @param mixed $parameters * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public static function find($parameters = null) {} + public static function find($parameters = null): ResultsetInterface {} /** * Query the first record that matches the specified conditions * - * + * ```php * // What's the first robot in robots table? * $robot = Robots::findFirst(); * @@ -521,7 +620,7 @@ public static function find($parameters = null) {} * * // What's the first mechanical robot in robots table? * $robot = Robots::findFirst( - * "type = 'mechanical'" + * "type = 'mechanical'" * ); * * echo "The first mechanical robot name is ", $robot->name; @@ -539,431 +638,414 @@ public static function find($parameters = null) {} * // behaviour with transaction * $myTransaction = new Transaction(\Phalcon\Di::getDefault()); * $myTransaction->begin(); + * * $newRobot = new Robot(); * $newRobot->setTransaction($myTransaction); - * $newRobot->save(['name' => 'test', 'type' => 'mechanical', 'year' => 1944]); + * $newRobot->assign( + * [ + * 'name' => 'test', + * 'type' => 'mechanical', + * 'year' => 1944, + * ] + * ); + * $newRobot->save(); + * + * $findsARobot = Robot::findFirst( + * [ + * 'name' => 'test', + * Model::TRANSACTION_INDEX => $myTransaction, + * ] + * ); * - * $findsARobot = Robot::findFirst(['name' => 'test', Model::TRANSACTION_INDEX => $myTransaction]); - * $doesNotFindARobot = Robot::findFirst(['name' => 'test']); + * $doesNotFindARobot = Robot::findFirst( + * [ + * 'name' => 'test', + * ] + * ); * * var_dump($findARobot); * var_dump($doesNotFindARobot); * * $transaction->commit(); - * $doesFindTheRobotNow = Robot::findFirst(['name' => 'test']); - * * - * @param mixed $parameters - * @return Model + * $doesFindTheRobotNow = Robot::findFirst( + * [ + * 'name' => 'test', + * ] + * ); + * ``` + * + * @param string|array $parameters + * @return bool|\Phalcon\Mvc\ModelInterface */ public static function findFirst($parameters = null) {} /** - * shared prepare query logic for find and findFirst method + * Fires an event, implicitly calls behaviors and listeners in the events + * manager are notified * - * @param mixed $params - * @param mixed $limit - * @return \Phalcon\Mvc\Model\Query + * @param string $eventName + * @return bool */ - private static function getPreparedQuery($params, $limit = null) {} + public function fireEvent(string $eventName): bool {} /** - * Create a criteria for a specific model + * Fires an event, implicitly calls behaviors and listeners in the events + * manager are notified + * This method stops if one of the callbacks/listeners returns bool false * - * @param \Phalcon\DiInterface $dependencyInjector - * @return \Phalcon\Mvc\Model\Criteria + * @param string $eventName + * @return bool */ - public static function query(\Phalcon\DiInterface $dependencyInjector = null) {} + public function fireEventCancel(string $eventName): bool {} /** - * Checks whether the current record already exists + * Returns a list of changed values. * - * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData - * @param \Phalcon\Db\AdapterInterface $connection - * @param string|array $table - * @return bool + * ```php + * $robots = Robots::findFirst(); + * print_r($robots->getChangedFields()); // [] + * + * $robots->deleted = 'Y'; + * + * $robots->getChangedFields(); + * print_r($robots->getChangedFields()); // ["deleted"] + * ``` + * + * @return array */ - protected function _exists(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\AdapterInterface $connection, $table = null) {} + public function getChangedFields(): array {} /** - * Generate a PHQL SELECT statement for an aggregate + * Returns one of the DIRTY_STATE_ constants telling if the record exists + * in the database or not * - * @param string $functionName - * @param string $alias - * @param array $parameters - * @param string $function - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @return int */ - protected static function _groupResult($functionName, $alias, $parameters) {} + public function getDirtyState(): int {} /** - * Counts how many records match the specified conditions - * - * - * // How many robots are there? - * $number = Robots::count(); - * - * echo "There are ", $number, "\n"; - * - * // How many mechanical robots are there? - * $number = Robots::count("type = 'mechanical'"); + * Returns the dependency injection container * - * echo "There are ", $number, " mechanical robots\n"; - * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Returns the custom events manager * - * @param array $parameters - * @return mixed + * @return \Phalcon\Events\ManagerInterface */ - public static function count($parameters = null) {} + public function getEventsManager(): EventsManagerInterface {} /** - * Calculates the sum on a column for a result-set of rows that match the specified conditions + * Returns array of validation messages * - * - * // How much are all robots? - * $sum = Robots::sum( - * [ - * "column" => "price", - * ] - * ); + * ```php + * $robot = new Robots(); * - * echo "The total price of robots is ", $sum, "\n"; + * $robot->type = "mechanical"; + * $robot->name = "Astro Boy"; + * $robot->year = 1952; * - * // How much are mechanical robots? - * $sum = Robots::sum( - * [ - * "type = 'mechanical'", - * "column" => "price", - * ] - * ); + * if ($robot->save() === false) { + * echo "Umh, We can't store robots right now "; * - * echo "The total price of mechanical robots is ", $sum, "\n"; - * + * $messages = $robot->getMessages(); * - * @param array $parameters - * @return mixed + * foreach ($messages as $message) { + * echo $message; + * } + * } else { + * echo "Great, a new robot was saved successfully!"; + * } + * ``` + * + * @param mixed $filter + * @return array|\Phalcon\Messages\MessageInterface[] */ - public static function sum($parameters = null) {} + public function getMessages($filter = null): array {} /** - * Returns the maximum value of a column for a result-set of rows that match the specified conditions - * - * - * // What is the maximum robot id? - * $id = Robots::maximum( - * [ - * "column" => "id", - * ] - * ); + * Returns the models manager related to the entity instance * - * echo "The maximum robot id is: ", $id, "\n"; + * @return \Phalcon\Mvc\Model\ManagerInterface + */ + public function getModelsManager(): ManagerInterface {} + + /** + * {@inheritdoc} * - * // What is the maximum id of mechanical robots? - * $sum = Robots::maximum( - * [ - * "type = 'mechanical'", - * "column" => "id", - * ] - * ); + * @return \Phalcon\Mvc\Model\MetaDataInterface + */ + public function getModelsMetaData(): MetaDataInterface {} + + /** + * Returns the type of the latest operation performed by the ORM + * Returns one of the OP_ class constants * - * echo "The maximum robot id of mechanical robots is ", $id, "\n"; - * + * @return int + */ + public function getOperationMade(): int {} + + /** + * Returns the internal old snapshot data * - * @param array $parameters - * @return mixed + * @return array */ - public static function maximum($parameters = null) {} + public function getOldSnapshotData(): array {} /** - * Returns the minimum value of a column for a result-set of rows that match the specified conditions + * Gets the connection used to read data for the model * - * - * // What is the minimum robot id? - * $id = Robots::minimum( - * [ - * "column" => "id", - * ] - * ); - * - * echo "The minimum robot id is: ", $id; - * - * // What is the minimum id of mechanical robots? - * $sum = Robots::minimum( - * [ - * "type = 'mechanical'", - * "column" => "id", - * ] - * ); + * @return \Phalcon\Db\Adapter\AdapterInterface + */ + final public function getReadConnection(): AdapterInterface {} + + /** + * Returns the DependencyInjection connection service name used to read data + * related the model * - * echo "The minimum robot id of mechanical robots is ", $id; - * + * @return string + */ + final public function getReadConnectionService(): string {} + + /** + * Returns related records based on defined relations * - * @param array $parameters - * @return mixed + * @param string $alias + * @param array $arguments + * @return \Phalcon\Mvc\Model\Resultset\Simple|Phalcon\Mvc\Model\Resultset\Simple|false */ - public static function minimum($parameters = null) {} + public function getRelated(string $alias, $arguments = null) {} /** - * Returns the average value on a column for a result-set of rows matching the specified conditions + * Checks if saved related records have already been loaded. * - * - * // What's the average price of robots? - * $average = Robots::average( - * [ - * "column" => "price", - * ] - * ); + * Only returns true if the records were previously fetched + * through the model without any additional parameters. * - * echo "The average price is ", $average, "\n"; + * ```php + * $robot = Robots::findFirst(); + * var_dump($robot->isRelationshipLoaded('robotsParts')); // false * - * // What's the average price of mechanical robots? - * $average = Robots::average( - * [ - * "type = 'mechanical'", - * "column" => "price", - * ] - * ); + * $robotsParts = $robot->getRobotsParts(['id > 0']); + * var_dump($robot->isRelationshipLoaded('robotsParts')); // false * - * echo "The average price of mechanical robots is ", $average, "\n"; - * + * $robotsParts = $robot->getRobotsParts(); // or $robot->robotsParts + * var_dump($robot->isRelationshipLoaded('robotsParts')); // true * - * @param array $parameters - * @return double + * $robot->robotsParts = [new RobotsParts()]; + * var_dump($robot->isRelationshipLoaded('robotsParts')); // false + * ``` + * + * @param string $relationshipAlias + * @return bool */ - public static function average($parameters = null) {} + public function isRelationshipLoaded(string $relationshipAlias): bool {} /** - * Fires an event, implicitly calls behaviors and listeners in the events manager are notified + * Returns schema name where the mapped table is located * - * @param string $eventName - * @return bool + * @return string */ - public function fireEvent($eventName) {} + final public function getSchema(): string {} /** - * Fires an event, implicitly calls behaviors and listeners in the events manager are notified - * This method stops if one of the callbacks/listeners returns boolean false + * Returns the internal snapshot data * - * @param string $eventName - * @return bool + * @return array */ - public function fireEventCancel($eventName) {} + public function getSnapshotData(): array {} /** - * Cancel the current operation + * Returns the table name mapped in the model + * + * @return string */ - protected function _cancelOperation() {} + final public function getSource(): string {} /** - * Appends a customized message on the validation process + * Returns a list of updated values. * - * - * use Phalcon\Mvc\Model; - * use Phalcon\Mvc\Model\Message as Message; + * ```php + * $robots = Robots::findFirst(); + * print_r($robots->getChangedFields()); // [] * - * class Robots extends Model - * { - * public function beforeSave() - * { - * if ($this->name === "Peter") { - * $message = new Message( - * "Sorry, but a robot cannot be named Peter" - * ); + * $robots->deleted = 'Y'; * - * $this->appendMessage($message); - * } - * } - * } - * + * $robots->getChangedFields(); + * print_r($robots->getChangedFields()); // ["deleted"] + * $robots->save(); + * print_r($robots->getChangedFields()); // [] + * print_r($robots->getUpdatedFields()); // ["deleted"] + * ``` * - * @param \Phalcon\Mvc\Model\MessageInterface $message - * @return Model + * @return array */ - public function appendMessage(\Phalcon\Mvc\Model\MessageInterface $message) {} + public function getUpdatedFields(): array {} /** - * Executes validators on every validation call - * - * - * use Phalcon\Mvc\Model; - * use Phalcon\Validation; - * use Phalcon\Validation\Validator\ExclusionIn; - * - * class Subscriptors extends Model - * { - * public function validation() - * { - * $validator = new Validation(); - * - * $validator->add( - * "status", - * new ExclusionIn( - * [ - * "domain" => [ - * "A", - * "I", - * ], - * ] - * ) - * ); - * - * return $this->validate($validator); - * } - * } - * + * Gets the connection used to write data to the model * - * @param \Phalcon\ValidationInterface $validator - * @return bool + * @return \Phalcon\Db\Adapter\AdapterInterface */ - protected function validate(\Phalcon\ValidationInterface $validator) {} + final public function getWriteConnection(): AdapterInterface {} /** - * Check whether validation process has generated any messages - * - * - * use Phalcon\Mvc\Model; - * use Phalcon\Validation; - * use Phalcon\Validation\Validator\ExclusionIn; - * - * class Subscriptors extends Model - * { - * public function validation() - * { - * $validator = new Validation(); - * - * $validator->validate( - * "status", - * new ExclusionIn( - * [ - * "domain" => [ - * "A", - * "I", - * ], - * ] - * ) - * ); - * - * return $this->validate($validator); - * } - * } - * + * Returns the DependencyInjection connection service name used to write + * data related to the model * - * @return bool + * @return string */ - public function validationHasFailed() {} + final public function getWriteConnectionService(): string {} /** - * Returns array of validation messages + * Check if a specific attribute has changed + * This only works if the model is keeping data snapshots * - * + * ```php * $robot = new Robots(); * * $robot->type = "mechanical"; * $robot->name = "Astro Boy"; * $robot->year = 1952; * - * if ($robot->save() === false) { - * echo "Umh, We can't store robots right now "; - * - * $messages = $robot->getMessages(); + * $robot->create(); * - * foreach ($messages as $message) { - * echo $message; - * } - * } else { - * echo "Great, a new robot was saved successfully!"; - * } - * + * $robot->type = "hydraulic"; * - * @param mixed $filter - * @return \Phalcon\Mvc\Model\MessageInterface[] - */ - public function getMessages($filter = null) {} - - /** - * Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records - * to verify that inserted/updated values are present in the related entity + * $hasChanged = $robot->hasChanged("type"); // returns true + * $hasChanged = $robot->hasChanged(["type", "name"]); // returns true + * $hasChanged = $robot->hasChanged(["type", "name"], true); // returns false + * ``` * + * @param string|array $fieldName + * @param boolean $allFields * @return bool */ - protected final function _checkForeignKeysRestrict() {} + public function hasChanged($fieldName = null, bool $allFields = false): bool {} /** - * Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (cascade) when deleting records + * Checks if the object has internal snapshot data * * @return bool */ - protected final function _checkForeignKeysReverseCascade() {} + public function hasSnapshotData(): bool {} /** - * Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (restrict) when deleting records + * Check if a specific attribute was updated + * This only works if the model is keeping data snapshots * + * @param string|array $fieldName + * @param bool $allFields * @return bool */ - protected final function _checkForeignKeysReverseRestrict() {} + public function hasUpdated($fieldName = null, bool $allFields = false): bool {} /** - * Executes internal hooks before save a record + * Serializes the object for json_encode * - * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData - * @param bool $exists - * @param mixed $identityField - * @return bool + * ```php + * echo json_encode($robot); + * ``` + * + * @return array */ - protected function _preSave(\Phalcon\Mvc\Model\MetaDataInterface $metaData, $exists, $identityField) {} + public function jsonSerialize(): array {} /** - * Executes internal events after save a record + * Returns the maximum value of a column for a result-set of rows that match + * the specified conditions * - * @param bool $success - * @param bool $exists - * @return bool + * ```php + * // What is the maximum robot id? + * $id = Robots::maximum( + * [ + * "column" => "id", + * ] + * ); + * + * echo "The maximum robot id is: ", $id, "\n"; + * + * // What is the maximum id of mechanical robots? + * $sum = Robots::maximum( + * [ + * "type = 'mechanical'", + * "column" => "id", + * ] + * ); + * + * echo "The maximum robot id of mechanical robots is ", $id, "\n"; + * ``` + * + * @param array $parameters + * @return mixed */ - protected function _postSave($success, $exists) {} + public static function maximum($parameters = null) {} /** - * Sends a pre-build INSERT SQL statement to the relational database system + * Returns the minimum value of a column for a result-set of rows that match + * the specified conditions * - * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData - * @param \Phalcon\Db\AdapterInterface $connection - * @param string|array $table - * @param boolean|string $identityField - * @return bool + * ```php + * // What is the minimum robot id? + * $id = Robots::minimum( + * [ + * "column" => "id", + * ] + * ); + * + * echo "The minimum robot id is: ", $id; + * + * // What is the minimum id of mechanical robots? + * $sum = Robots::minimum( + * [ + * "type = 'mechanical'", + * "column" => "id", + * ] + * ); + * + * echo "The minimum robot id of mechanical robots is ", $id; + * ``` + * + * @param array $parameters + * @return mixed */ - protected function _doLowInsert(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\AdapterInterface $connection, $table, $identityField) {} + public static function minimum($parameters = null) {} /** - * Sends a pre-build UPDATE SQL statement to the relational database system + * Create a criteria for a specific model * - * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData - * @param \Phalcon\Db\AdapterInterface $connection - * @param string|array $table - * @return bool + * @param \Phalcon\Di\DiInterface $container + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - protected function _doLowUpdate(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\AdapterInterface $connection, $table) {} + public static function query(\Phalcon\Di\DiInterface $container = null): CriteriaInterface {} /** - * Saves related records that must be stored prior to save the master record + * Reads an attribute value by its name * - * @param \Phalcon\Db\AdapterInterface $connection - * @param \Phalcon\Mvc\ModelInterface[] $related - * @return bool + * ```php + * echo $robot->readAttribute("name"); + * ``` + * + * @param string $attribute + * @return mixed|null */ - protected function _preSaveRelatedRecords(\Phalcon\Db\AdapterInterface $connection, $related) {} + public function readAttribute(string $attribute): ? {} /** - * Save the related records assigned in the has-one/has-many relations + * Refreshes the model attributes re-querying the record from the database * - * @param \Phalcon\Db\AdapterInterface $connection - * @param \Phalcon\Mvc\ModelInterface[] $related - * @return bool + * @return \Phalcon\Mvc\ModelInterface */ - protected function _postSaveRelatedRecords(\Phalcon\Db\AdapterInterface $connection, $related) {} + public function refresh(): ModelInterface {} /** - * Inserts or updates a model instance. Returning true on success or false otherwise. + * Inserts or updates a model instance. Returning true on success or false + * otherwise. * - * + * ```php * // Creating a new robot * $robot = new Robots(); * @@ -979,648 +1061,697 @@ protected function _postSaveRelatedRecords(\Phalcon\Db\AdapterInterface $connect * $robot->name = "Biomass"; * * $robot->save(); - * + * ``` * - * @param array $data - * @param array $whiteList * @return bool */ - public function save($data = null, $whiteList = null) {} + public function save(): bool {} /** - * Inserts a model instance. If the instance already exists in the persistence it will throw an exception - * Returning true on success or false otherwise. - * - * - * // Creating a new robot - * $robot = new Robots(); + * Serializes the object ignoring connections, services, related objects or + * static properties * - * $robot->type = "mechanical"; - * $robot->name = "Astro Boy"; - * $robot->year = 1952; - * - * $robot->create(); - * - * // Passing an array to create - * $robot = new Robots(); - * - * $robot->create( - * [ - * "type" => "mechanical", - * "name" => "Astro Boy", - * "year" => 1952, - * ] - * ); - * - * - * @param mixed $data - * @param mixed $whiteList - * @return bool + * @return string */ - public function create($data = null, $whiteList = null) {} + public function serialize(): string {} /** - * Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception - * Returning true on success or false otherwise. - * - * - * // Updating a robot name - * $robot = Robots::findFirst("id = 100"); - * - * $robot->name = "Biomass"; - * - * $robot->update(); - * + * Unserializes the object from a serialized string * * @param mixed $data - * @param mixed $whiteList - * @return bool */ - public function update($data = null, $whiteList = null) {} + public function unserialize($data) {} /** - * Deletes a model instance. Returning true on success or false otherwise. - * - * - * $robot = Robots::findFirst("id=100"); - * - * $robot->delete(); - * - * $robots = Robots::find("type = 'mechanical'"); - * - * foreach ($robots as $robot) { - * $robot->delete(); - * } - * + * Sets the DependencyInjection connection service name * - * @return bool + * @param string $connectionService + * @return \Phalcon\Mvc\ModelInterface */ - public function delete() {} + final public function setConnectionService(string $connectionService): ModelInterface {} /** - * Returns the type of the latest operation performed by the ORM - * Returns one of the OP_ class constants + * Sets the dirty state of the object using one of the DIRTY_STATE_ constants * - * @return int + * @param int $dirtyState + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function getOperationMade() {} + public function setDirtyState(int $dirtyState) {} /** - * Refreshes the model attributes re-querying the record from the database + * Sets the dependency injection container * - * @return Model + * @param \Phalcon\Di\DiInterface $container */ - public function refresh() {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Skips the current operation forcing a success state + * Sets a custom events manager * - * @param bool $skip + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function skipOperation($skip) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Reads an attribute value by its name - * - * - * echo $robot->readAttribute("name"); - * + * Sets the DependencyInjection connection service name used to read data * - * @param string $attribute + * @param string $connectionService + * @return \Phalcon\Mvc\ModelInterface */ - public function readAttribute($attribute) {} + final public function setReadConnectionService(string $connectionService): ModelInterface {} /** - * Writes an attribute value by its name + * Sets the record's old snapshot data. + * This method is used internally to set old snapshot data when the model + * was set up to keep snapshot data * - * - * $robot->writeAttribute("name", "Rosey"); - * + * @param array $data + * @param array $columnMap + */ + public function setOldSnapshotData(array $data, $columnMap = null) {} + + /** + * Sets the record's snapshot data. + * This method is used internally to set snapshot data when the model was + * set up to keep snapshot data * - * @param string $attribute - * @param mixed $value + * @param array $data + * @param array $columnMap */ - public function writeAttribute($attribute, $value) {} + public function setSnapshotData(array $data, $columnMap = null) {} /** - * Sets a list of attributes that must be skipped from the - * generated INSERT/UPDATE statement + * Sets a transaction related to the Model instance * - * + * ```php + * use Phalcon\Mvc\Model\Transaction\Manager as TxManager; + * use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->skipAttributes( - * [ - * "price", - * ] - * ); + * try { + * $txManager = new TxManager(); + * + * $transaction = $txManager->get(); + * + * $robot = new Robots(); + * + * $robot->setTransaction($transaction); + * + * $robot->name = "WALL·E"; + * $robot->created_at = date("Y-m-d"); + * + * if ($robot->save() === false) { + * $transaction->rollback("Can't save robot"); * } - * } - * * - * @param array $attributes - */ - protected function skipAttributes(array $attributes) {} - - /** - * Sets a list of attributes that must be skipped from the - * generated INSERT statement + * $robotPart = new RobotParts(); * - * + * $robotPart->setTransaction($transaction); * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->skipAttributesOnCreate( - * [ - * "created_at", - * ] - * ); + * $robotPart->type = "head"; + * + * if ($robotPart->save() === false) { + * $transaction->rollback("Robot part cannot be saved"); * } + * + * $transaction->commit(); + * } catch (TxFailed $e) { + * echo "Failed, reason: ", $e->getMessage(); * } - * + * ``` * - * @param array $attributes + * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @return \Phalcon\Mvc\ModelInterface */ - protected function skipAttributesOnCreate(array $attributes) {} + public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction): ModelInterface {} /** - * Sets a list of attributes that must be skipped from the - * generated UPDATE statement + * Enables/disables options in the ORM * - * + * @param array $options + */ + public static function setup(array $options) {} + + /** + * Sets the DependencyInjection connection service name used to write data * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->skipAttributesOnUpdate( - * [ - * "modified_in", - * ] - * ); - * } - * } - * + * @param string $connectionService + * @return \Phalcon\Mvc\ModelInterface + */ + final public function setWriteConnectionService(string $connectionService): ModelInterface {} + + /** + * Skips the current operation forcing a success state * - * @param array $attributes + * @param bool $skip */ - protected function skipAttributesOnUpdate(array $attributes) {} + public function skipOperation(bool $skip) {} /** - * Sets a list of attributes that must be skipped from the - * generated UPDATE statement + * Calculates the sum on a column for a result-set of rows that match the + * specified conditions * - * + * ```php + * // How much are all robots? + * $sum = Robots::sum( + * [ + * "column" => "price", + * ] + * ); * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->allowEmptyStringValues( - * [ - * "name", - * ] - * ); - * } - * } - * + * echo "The total price of robots is ", $sum, "\n"; * - * @param array $attributes + * // How much are mechanical robots? + * $sum = Robots::sum( + * [ + * "type = 'mechanical'", + * "column" => "price", + * ] + * ); + * + * echo "The total price of mechanical robots is ", $sum, "\n"; + * ``` + * + * @param array $parameters + * @return double */ - protected function allowEmptyStringValues(array $attributes) {} + public static function sum($parameters = null): float {} /** - * Setup a 1-1 relation between two models - * - * + * Returns the instance as an array representation * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->hasOne("id", "RobotsDescription", "robots_id"); - * } - * } - * + * ```php + * print_r( + * $robot->toArray() + * ); + * ``` * - * @param mixed $fields - * @param string $referenceModel - * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\Relation + * @param array $columns + * @return array */ - protected function hasOne($fields, $referenceModel, $referencedFields, $options = null) {} + public function toArray($columns = null): array {} /** - * Setup a reverse 1-1 or n-1 relation between two models + * Updates a model instance. If the instance doesn't exist in the + * persistence it will throw an exception. Returning true on success or + * false otherwise. * - * + * ```php + * // Updating a robot name + * $robot = Robots::findFirst("id = 100"); * - * class RobotsParts extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->belongsTo("robots_id", "Robots", "id"); - * } - * } - * + * $robot->name = "Biomass"; * - * @param mixed $fields - * @param string $referenceModel - * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\Relation + * $robot->update(); + * ``` + * + * @return bool */ - protected function belongsTo($fields, $referenceModel, $referencedFields, $options = null) {} + public function update(): bool {} /** - * Setup a 1-n relation between two models - * - * + * Writes an attribute value by its name * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * $this->hasMany("id", "RobotsParts", "robots_id"); - * } - * } - * + * ```php + * $robot->writeAttribute("name", "Rosey"); + * ``` * - * @param mixed $fields - * @param string $referenceModel - * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\Relation + * @param string $attribute + * @param mixed $value */ - protected function hasMany($fields, $referenceModel, $referencedFields, $options = null) {} + public function writeAttribute(string $attribute, $value) {} /** - * Setup an n-n relation between two models, through an intermediate relation + * Reads "belongs to" relations and check the virtual foreign keys when + * inserting or updating records to verify that inserted/updated values are + * present in the related entity * - * - * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function initialize() - * { - * // Setup a many-to-many relation to Parts through RobotsParts - * $this->hasManyToMany( - * "id", - * "RobotsParts", - * "robots_id", - * "parts_id", - * "Parts", - * "id", - * ); - * } - * } - * - * - * @param string|array fields - * @param string intermediateModel - * @param string|array intermediateFields - * @param string|array intermediateReferencedFields - * @param string referencedModel - * @param mixed $fields - * @param string $intermediateModel - * @param mixed $intermediateFields - * @param mixed $intermediateReferencedFields - * @param string $referenceModel - * @param string|array $referencedFields - * @param array $options - * @return \Phalcon\Mvc\Model\Relation + * @return bool */ - protected function hasManyToMany($fields, $intermediateModel, $intermediateFields, $intermediateReferencedFields, $referenceModel, $referencedFields, $options = null) {} + final protected function _checkForeignKeysRestrict(): bool {} /** - * Setups a behavior in a model + * Reads both "hasMany" and "hasOne" relations and checks the virtual + * foreign keys (cascade) when deleting records * - * - * - * use Phalcon\Mvc\Model; - * use Phalcon\Mvc\Model\Behavior\Timestampable; - * - * class Robots extends Model - * { - * public function initialize() - * { - * $this->addBehavior( - * new Timestampable( - * [ - * "onCreate" => [ - * "field" => "created_at", - * "format" => "Y-m-d", - * ], - * ] - * ) - * ); - * } - * } - * - * - * @param \Phalcon\Mvc\Model\BehaviorInterface $behavior + * @return bool */ - public function addBehavior(\Phalcon\Mvc\Model\BehaviorInterface $behavior) {} + final protected function _checkForeignKeysReverseCascade(): bool {} /** - * Sets if the model must keep the original record snapshot in memory - * - * - * - * use Phalcon\Mvc\Model; - * - * class Robots extends Model - * { - * public function initialize() - * { - * $this->keepSnapshots(true); - * } - * } - * + * Reads both "hasMany" and "hasOne" relations and checks the virtual + * foreign keys (restrict) when deleting records * - * @param bool $keepSnapshot + * @return bool */ - protected function keepSnapshots($keepSnapshot) {} + final protected function _checkForeignKeysReverseRestrict(): bool {} /** - * Sets the record's snapshot data. - * This method is used internally to set snapshot data when the model was set up to keep snapshot data + * Sends a pre-build INSERT SQL statement to the relational database system * - * @param array $data - * @param array $columnMap + * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData + * @param \Phalcon\Db\Adapter\AdapterInterface $connection + * @param string|array $table + * @param bool|string $identityField + * @return bool */ - public function setSnapshotData(array $data, $columnMap = null) {} + protected function _doLowInsert(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\Adapter\AdapterInterface $connection, $table, $identityField): bool {} /** - * Sets the record's old snapshot data. - * This method is used internally to set old snapshot data when the model was set up to keep snapshot data + * Sends a pre-build UPDATE SQL statement to the relational database system * - * @param array $data - * @param array $columnMap + * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData + * @param \Phalcon\Db\Adapter\AdapterInterface $connection + * @param string|array $table + * @return bool */ - public function setOldSnapshotData(array $data, $columnMap = null) {} + protected function _doLowUpdate(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\Adapter\AdapterInterface $connection, $table): bool {} /** - * Checks if the object has internal snapshot data + * Checks whether the current record already exists * + * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData + * @param \Phalcon\Db\Adapter\AdapterInterface $connection * @return bool */ - public function hasSnapshotData() {} + protected function _exists(\Phalcon\Mvc\Model\MetaDataInterface $metaData, \Phalcon\Db\Adapter\AdapterInterface $connection): bool {} /** - * Returns the internal snapshot data + * Returns related records defined relations depending on the method name * - * @return array + * @param string $modelName + * @param string $method + * @param array $arguments + * @return mixed */ - public function getSnapshotData() {} + protected function _getRelatedRecords(string $modelName, string $method, $arguments) {} /** - * Returns the internal old snapshot data + * Generate a PHQL SELECT statement for an aggregate * - * @return array + * @param string $functionName + * @param string $alias + * @param array $parameters + * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public function getOldSnapshotData() {} + protected static function _groupResult(string $functionName, string $alias, $parameters): ResultsetInterface {} /** - * Check if a specific attribute has changed - * This only works if the model is keeping data snapshots - * - * - * $robot = new Robots(); - * - * $robot->type = "mechanical"; - * $robot->name = "Astro Boy"; - * $robot->year = 1952; + * Try to check if the query must invoke a finder * - * $robot->create(); - * $robot->type = "hydraulic"; - * $hasChanged = $robot->hasChanged("type"); // returns true - * $hasChanged = $robot->hasChanged(["type", "name"]); // returns true - * $hasChanged = $robot->hasChanged(["type", "name", true]); // returns false - * + * @param string $method + * @param array $arguments + * @return \Phalcon\Mvc\ModelInterface[]|\Phalcon\Mvc\ModelInterface|bool + */ + protected final static function _invokeFinder(string $method, array $arguments) {} + + /** + * Check for, and attempt to use, possible setter. * - * @param string|array $fieldName - * @param boolean $allFields + * @param string $property + * @param mixed $value * @return bool */ - public function hasChanged($fieldName = null, $allFields = false) {} + final protected function _possibleSetter(string $property, $value): bool {} /** - * Check if a specific attribute was updated - * This only works if the model is keeping data snapshots + * Executes internal hooks before save a record * - * @param string|array $fieldName - * @param bool $allFields + * @param \Phalcon\Mvc\Model\MetaDataInterface $metaData + * @param bool $exists + * @param mixed $identityField * @return bool */ - public function hasUpdated($fieldName = null, $allFields = false) {} + protected function _preSave(\Phalcon\Mvc\Model\MetaDataInterface $metaData, bool $exists, $identityField): bool {} /** - * Returns a list of changed values. - * - * - * $robots = Robots::findFirst(); - * print_r($robots->getChangedFields()); // [] - * - * $robots->deleted = 'Y'; - * - * $robots->getChangedFields(); - * print_r($robots->getChangedFields()); // ["deleted"] - * + * Saves related records that must be stored prior to save the master record * - * @return array + * @param \Phalcon\Db\Adapter\AdapterInterface $connection + * @param \Phalcon\Mvc\ModelInterface[] $related + * @return bool */ - public function getChangedFields() {} + protected function _preSaveRelatedRecords(\Phalcon\Db\Adapter\AdapterInterface $connection, $related): bool {} /** - * Returns a list of updated values. - * - * - * $robots = Robots::findFirst(); - * print_r($robots->getChangedFields()); // [] - * - * $robots->deleted = 'Y'; + * Executes internal events after save a record * - * $robots->getChangedFields(); - * print_r($robots->getChangedFields()); // ["deleted"] - * $robots->save(); - * print_r($robots->getChangedFields()); // [] - * print_r($robots->getUpdatedFields()); // ["deleted"] - * + * @param bool $success + * @param bool $exists + * @return bool */ - public function getUpdatedFields() {} + protected function _postSave(bool $success, bool $exists): bool {} /** - * Sets if a model must use dynamic update instead of the all-field update - * - * + * Save the related records assigned in the has-one/has-many relations * - * use Phalcon\Mvc\Model; + * @param \Phalcon\Db\Adapter\AdapterInterface $connection + * @param \Phalcon\Mvc\ModelInterface[] $related + * @return bool + */ + protected function _postSaveRelatedRecords(\Phalcon\Db\Adapter\AdapterInterface $connection, $related): bool {} + + /** + * Sets a list of attributes that must be skipped from the + * generated UPDATE statement * - * class Robots extends Model + * ```php + * class Robots extends \Phalcon\Mvc\Model * { * public function initialize() * { - * $this->useDynamicUpdate(true); + * $this->allowEmptyStringValues( + * [ + * "name", + * ] + * ); * } * } - * + * ``` * - * @param bool $dynamicUpdate + * @param array $attributes */ - protected function useDynamicUpdate($dynamicUpdate) {} + protected function allowEmptyStringValues(array $attributes) {} /** - * Returns related records based on defined relations - * - * @param string $alias - * @param array $arguments - * @return \Phalcon\Mvc\Model\ResultsetInterface + * Cancel the current operation */ - public function getRelated($alias, $arguments = null) {} + protected function _cancelOperation() {} /** - * Returns related records defined relations depending on the method name + * Setup a reverse 1-1 or n-1 relation between two models * - * @param string $modelName - * @param string $method - * @param array $arguments - * @return mixed + * ```php + * class RobotsParts extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->belongsTo( + * "robots_id", + * Robots::class, + * "id" + * ); + * } + * } + * ``` + * + * @param mixed $fields + * @param string $referenceModel + * @param mixed $referencedFields + * @param mixed $options + * @return \Phalcon\Mvc\Model\Relation */ - protected function _getRelatedRecords($modelName, $method, $arguments) {} + protected function belongsTo($fields, string $referenceModel, $referencedFields, $options = null): Relation {} /** - * Try to check if the query must invoke a finder + * shared prepare query logic for find and findFirst method * - * @param string $method - * @param array $arguments - * @return \Phalcon\Mvc\ModelInterface[]|\Phalcon\Mvc\ModelInterface|boolean + * @param mixed $params + * @param mixed $limit + * @return \Phalcon\Mvc\Model\Query */ - protected final static function _invokeFinder($method, $arguments) {} + private static function getPreparedQuery($params, $limit = null): Query {} /** - * Handles method calls when a method is not implemented + * Setup a 1-n relation between two models * - * @param string method - * @param array arguments - * @return mixed - * @param string $method - * @param mixed $arguments + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->hasMany( + * "id", + * RobotsParts::class, + * "robots_id" + * ); + * } + * } + * ``` + * + * @param mixed $fields + * @param string $referenceModel + * @param mixed $referencedFields + * @param mixed $options + * @return \Phalcon\Mvc\Model\Relation */ - public function __call($method, $arguments) {} + protected function hasMany($fields, string $referenceModel, $referencedFields, $options = null): Relation {} /** - * Handles method calls when a static method is not implemented + * Setup an n-n relation between two models, through an intermediate + * relation * - * @param string method - * @param array arguments - * @return mixed - * @param string $method - * @param mixed $arguments + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * // Setup a many-to-many relation to Parts through RobotsParts + * $this->hasManyToMany( + * "id", + * RobotsParts::class, + * "robots_id", + * "parts_id", + * Parts::class, + * "id", + * ); + * } + * } + * ``` + * + * @param string|array $fields + * @param string $intermediateModel + * @param string|array $intermediateFields + * @param string|array $intermediateReferencedFields + * @param string $referenceModel + * @param string|array $referencedFields + * @param array $options + * @return \Phalcon\Mvc\Model\Relation */ - public static function __callStatic($method, $arguments) {} + protected function hasManyToMany($fields, string $intermediateModel, $intermediateFields, $intermediateReferencedFields, string $referenceModel, $referencedFields, $options = null): Relation {} /** - * Magic method to assign values to the the model + * Setup a 1-1 relation between two models * - * @param string $property - * @param mixed $value + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->hasOne( + * "id", + * RobotsDescription::class, + * "robots_id" + * ); + * } + * } + * ``` + * + * @param mixed $fields + * @param string $referenceModel + * @param mixed $referencedFields + * @param mixed $options + * @return \Phalcon\Mvc\Model\Relation */ - public function __set($property, $value) {} + protected function hasOne($fields, string $referenceModel, $referencedFields, $options = null): Relation {} /** - * Check for, and attempt to use, possible setter. + * Sets if the model must keep the original record snapshot in memory * - * @param string $property - * @param mixed $value - * @return string + * ```php + * use Phalcon\Mvc\Model; + * + * class Robots extends Model + * { + * public function initialize() + * { + * $this->keepSnapshots(true); + * } + * } + * ``` + * + * @param bool $keepSnapshot */ - protected final function _possibleSetter($property, $value) {} + protected function keepSnapshots(bool $keepSnapshot) {} /** - * Magic method to get related records using the relation alias as a property + * Sets schema name where the mapped table is located * - * @param string $property - * @return \Phalcon\Mvc\Model\Resultset|Phalcon\Mvc\Model + * @param string $schema + * @return \Phalcon\Mvc\ModelInterface */ - public function __get($property) {} + final protected function setSchema(string $schema): ModelInterface {} /** - * Magic method to check if a property is a valid relation + * Sets the table name to which model should be mapped * - * @param string $property - * @return bool + * @param string $source + * @return \Phalcon\Mvc\ModelInterface */ - public function __isset($property) {} + final protected function setSource(string $source): ModelInterface {} /** - * Serializes the object ignoring connections, services, related objects or static properties + * Sets a list of attributes that must be skipped from the + * generated INSERT/UPDATE statement * - * @return string + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->skipAttributes( + * [ + * "price", + * ] + * ); + * } + * } + * ``` + * + * @param array $attributes */ - public function serialize() {} + protected function skipAttributes(array $attributes) {} /** - * Unserializes the object from a serialized string + * Sets a list of attributes that must be skipped from the + * generated INSERT statement * - * @param mixed $data + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->skipAttributesOnCreate( + * [ + * "created_at", + * ] + * ); + * } + * } + * ``` + * + * @param array $attributes */ - public function unserialize($data) {} + protected function skipAttributesOnCreate(array $attributes) {} /** - * Returns a simple representation of the object that can be used with var_dump + * Sets a list of attributes that must be skipped from the + * generated UPDATE statement * - * - * var_dump( - * $robot->dump() - * ); - * + * ```php + * class Robots extends \Phalcon\Mvc\Model + * { + * public function initialize() + * { + * $this->skipAttributesOnUpdate( + * [ + * "modified_in", + * ] + * ); + * } + * } + * ``` * - * @return array + * @param array $attributes */ - public function dump() {} + protected function skipAttributesOnUpdate(array $attributes) {} /** - * Returns the instance as an array representation + * Sets if a model must use dynamic update instead of the all-field update * - * - * print_r( - * $robot->toArray() - * ); - * + * ```php + * use Phalcon\Mvc\Model; * - * @param array $columns - * @return array + * class Robots extends Model + * { + * public function initialize() + * { + * $this->useDynamicUpdate(true); + * } + * } + * ``` + * + * @param bool $dynamicUpdate */ - public function toArray($columns = null) {} + protected function useDynamicUpdate(bool $dynamicUpdate) {} /** - * Serializes the object for json_encode + * Executes validators on every validation call * - * - * echo json_encode($robot); - * + * ```php + * use Phalcon\Mvc\Model; + * use Phalcon\Validation; + * use Phalcon\Validation\Validator\ExclusionIn; * - * @return array + * class Subscriptors extends Model + * { + * public function validation() + * { + * $validator = new Validation(); + * + * $validator->add( + * "status", + * new ExclusionIn( + * [ + * "domain" => [ + * "A", + * "I", + * ], + * ] + * ) + * ); + * + * return $this->validate($validator); + * } + * } + * ``` + * + * @param \Phalcon\Validation\ValidationInterface $validator + * @return bool */ - public function jsonSerialize() {} + protected function validate(\Phalcon\Validation\ValidationInterface $validator): bool {} /** - * Enables/disables options in the ORM + * Check whether validation process has generated any messages * - * @param array $options + * ```php + * use Phalcon\Mvc\Model; + * use Phalcon\Validation; + * use Phalcon\Validation\Validator\ExclusionIn; + * + * class Subscriptors extends Model + * { + * public function validation() + * { + * $validator = new Validation(); + * + * $validator->validate( + * "status", + * new ExclusionIn( + * [ + * "domain" => [ + * "A", + * "I", + * ], + * ] + * ) + * ); + * + * return $this->validate($validator); + * } + * } + * ``` + * + * @return bool */ - public static function setup(array $options) {} + public function validationHasFailed(): bool {} /** - * Reset a model instance data + * Attempts to find key case-insensitively + * + * @param mixed $columnMap + * @param mixed $key + * @return string */ - public function reset() {} + private static function caseInsensitiveColumnMap($columnMap, $key): string {} } diff --git a/src/Phalcon/mvc/ModelInterface.php b/src/Phalcon/mvc/ModelInterface.php index 5ded0692..b65f6f6d 100644 --- a/src/Phalcon/mvc/ModelInterface.php +++ b/src/Phalcon/mvc/ModelInterface.php @@ -11,313 +11,321 @@ interface ModelInterface { /** - * Sets a transaction related to the Model instance + * Appends a customized message on the validation process * - * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @param \Phalcon\Messages\MessageInterface $message * @return \Phalcon\Mvc\ModelInterface */ - public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction); + public function appendMessage(\Phalcon\Messages\MessageInterface $message): ModelInterface; /** - * Returns table name mapped in the model + * Assigns values to a model from an array * - * @return string + * @param array $data + * @param mixed $dataColumnMap + * @param mixed $whiteList + * @param array $columnMap + * @return \Phalcon\Mvc\ModelInterface */ - public function getSource(); + public function assign(array $data, $dataColumnMap = null, $whiteList = null): ModelInterface; /** - * Returns schema name where table mapped is located + * Allows to calculate the average value on a column matching the specified + * conditions * - * @return string + * @param array $parameters + * @return double */ - public function getSchema(); + public static function average($parameters = null): float; /** - * Sets both read/write connection services + * Assigns values to a model from an array returning a new model * - * @param string $connectionService + * @param \Phalcon\Mvc\ModelInterface $base + * @param array $data + * @param int $dirtyState + * @return \Phalcon\Mvc\ModelInterface */ - public function setConnectionService($connectionService); + public static function cloneResult(\Phalcon\Mvc\ModelInterface $base, array $data, int $dirtyState = 0): ModelInterface; /** - * Sets the DependencyInjection connection service used to write data + * Assigns values to a model from an array returning a new model * - * @param string $connectionService + * @param \Phalcon\Mvc\Model $base + * @param array $data + * @param array $columnMap + * @param int $dirtyState + * @param bool $keepSnapshots + * @return \Phalcon\Mvc\ModelInterface */ - public function setWriteConnectionService($connectionService); + public static function cloneResultMap($base, array $data, $columnMap, int $dirtyState = 0, bool $keepSnapshots = null): ModelInterface; /** - * Sets the DependencyInjection connection service used to read data + * Returns an hydrated result based on the data and the column map * - * @param string $connectionService + * @param array $data + * @param array $columnMap + * @param int $hydrationMode */ - public function setReadConnectionService($connectionService); + public static function cloneResultMapHydrate(array $data, $columnMap, int $hydrationMode); /** - * Returns DependencyInjection connection service used to read data + * Allows to count how many records match the specified conditions * - * @return string + * @param array $parameters + * @return int */ - public function getReadConnectionService(); + public static function count($parameters = null): int; /** - * Returns DependencyInjection connection service used to write data + * Inserts a model instance. If the instance already exists in the + * persistence it will throw an exception. Returning true on success or + * false otherwise. * - * @return string + * @return bool */ - public function getWriteConnectionService(); + public function create(): bool; /** - * Gets internal database connection + * Deletes a model instance. Returning true on success or false otherwise. * - * @return \Phalcon\Db\AdapterInterface + * @return bool */ - public function getReadConnection(); + public function delete(): bool; /** - * Gets internal database connection + * Allows to query a set of records that match the specified conditions * - * @return \Phalcon\Db\AdapterInterface + * @param mixed $parameters + * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public function getWriteConnection(); + public static function find($parameters = null): ResultsetInterface; /** - * Sets the dirty state of the object using one of the DIRTY_STATE_ constants + * Allows to query the first record that match the specified conditions * - * @param int $dirtyState - * @return \Phalcon\Mvc\ModelInterface + * @param array $parameters + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function setDirtyState($dirtyState); + public static function findFirst($parameters = null); /** - * Returns one of the DIRTY_STATE_ constants telling if the record exists in the database or not + * Fires an event, implicitly calls behaviors and listeners in the events + * manager are notified * - * @return int + * @param string $eventName + * @return bool */ - public function getDirtyState(); + public function fireEvent(string $eventName): bool; /** - * Assigns values to a model from an array + * Fires an event, implicitly calls behaviors and listeners in the events + * manager are notified. This method stops if one of the callbacks/listeners + * returns bool false * - * @param array $data - * @param mixed $dataColumnMap - * @param mixed $whiteList - * @param \Phalcon\Mvc\Model $object - * @param array $columnMap - * @return \Phalcon\Mvc\Model + * @param string $eventName + * @return bool */ - public function assign(array $data, $dataColumnMap = null, $whiteList = null); + public function fireEventCancel(string $eventName): bool; /** - * Assigns values to a model from an array returning a new model + * Returns one of the DIRTY_STATE_ constants telling if the record exists + * in the database or not * - * @param \Phalcon\Mvc\Model $base - * @param array $data - * @param array $columnMap - * @param int $dirtyState - * @param boolean $keepSnapshots - * @return \Phalcon\Mvc\Model + * @return int */ - public static function cloneResultMap($base, array $data, $columnMap, $dirtyState = 0, $keepSnapshots = null); + public function getDirtyState(): int; /** - * Assigns values to a model from an array returning a new model + * Returns array of validation messages * - * @param \Phalcon\Mvc\ModelInterface $base - * @param array $data - * @param int $dirtyState - * @return \Phalcon\Mvc\ModelInterface + * @return array|\Phalcon\Messages\MessageInterface[] */ - public static function cloneResult(\Phalcon\Mvc\ModelInterface $base, array $data, $dirtyState = 0); + public function getMessages(): array; /** - * Returns an hydrated result based on the data and the column map + * Returns the models meta-data service related to the entity instance. * - * @param array $data - * @param array $columnMap - * @param int $hydrationMode + * @return \Phalcon\Mvc\Model\MetaDataInterface */ - public static function cloneResultMapHydrate(array $data, $columnMap, $hydrationMode); + public function getModelsMetaData(): MetaDataInterface; /** - * Allows to query a set of records that match the specified conditions + * Returns the type of the latest operation performed by the ORM + * Returns one of the OP_ class constants * - * @param mixed $parameters - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @return int */ - public static function find($parameters = null); + public function getOperationMade(): int; /** - * Allows to query the first record that match the specified conditions + * Gets internal database connection * - * @param array $parameters - * @return static + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public static function findFirst($parameters = null); + public function getReadConnection(): AdapterInterface; /** - * Create a criteria for a specific model + * Returns DependencyInjection connection service used to read data * - * @param \Phalcon\DiInterface $dependencyInjector - * @return \Phalcon\Mvc\Model\CriteriaInterface + * @return string */ - public static function query(\Phalcon\DiInterface $dependencyInjector = null); + public function getReadConnectionService(): string; /** - * Allows to count how many records match the specified conditions + * Returns related records based on defined relations * - * @param array $parameters - * @return int + * @param string $alias + * @param array $arguments + * @return \Phalcon\Mvc\Model\Resultset\Simple|Phalcon\Mvc\Model\Resultset\Simple|false */ - public static function count($parameters = null); + public function getRelated(string $alias, $arguments = null); /** - * Allows to calculate a sum on a column that match the specified conditions + * Returns schema name where table mapped is located * - * @param array $parameters - * @return double + * @return string */ - public static function sum($parameters = null); + public function getSchema(): string; /** - * Allows to get the maximum value of a column that match the specified conditions + * Returns table name mapped in the model * - * @param array $parameters - * @return mixed + * @return string */ - public static function maximum($parameters = null); + public function getSource(): string; /** - * Allows to get the minimum value of a column that match the specified conditions + * Gets internal database connection * - * @param array $parameters - * @return mixed + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public static function minimum($parameters = null); + public function getWriteConnection(): AdapterInterface; /** - * Allows to calculate the average value on a column matching the specified conditions + * Returns DependencyInjection connection service used to write data * - * @param array $parameters - * @return double + * @return string */ - public static function average($parameters = null); + public function getWriteConnectionService(): string; /** - * Fires an event, implicitly calls behaviors and listeners in the events manager are notified + * Allows to get the maximum value of a column that match the specified + * conditions * - * @param string $eventName - * @return boolean + * @param array $parameters + * @return mixed */ - public function fireEvent($eventName); + public static function maximum($parameters = null); /** - * Fires an event, implicitly calls behaviors and listeners in the events manager are notified - * This method stops if one of the callbacks/listeners returns boolean false + * Allows to get the minimum value of a column that match the specified + * conditions * - * @param string $eventName - * @return boolean + * @param array $parameters + * @return mixed */ - public function fireEventCancel($eventName); + public static function minimum($parameters = null); /** - * Appends a customized message on the validation process + * Create a criteria for a specific model * - * @param \Phalcon\Mvc\Model\MessageInterface $message + * @param \Phalcon\Di\DiInterface $container + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function appendMessage(\Phalcon\Mvc\Model\MessageInterface $message); + public static function query(\Phalcon\Di\DiInterface $container = null): CriteriaInterface; /** - * Check whether validation process has generated any messages + * Refreshes the model attributes re-querying the record from the database * - * @return boolean + * @return \Phalcon\Mvc\ModelInterface */ - public function validationHasFailed(); + public function refresh(): ModelInterface; /** - * Returns array of validation messages + * Inserts or updates a model instance. Returning true on success or false + * otherwise. * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return bool */ - public function getMessages(); + public function save(): bool; /** - * Inserts or updates a model instance. Returning true on success or false otherwise. + * Sets both read/write connection services * - * @param array $data - * @param array $whiteList - * @return boolean + * @param string $connectionService */ - public function save($data = null, $whiteList = null); + public function setConnectionService(string $connectionService); /** - * Inserts a model instance. If the instance already exists in the persistence it will throw an exception - * Returning true on success or false otherwise. + * Sets the dirty state of the object using one of the DIRTY_STATE_ + * constants * - * @param array $data - * @param array $whiteList - * @return boolean + * @param int $dirtyState + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function create($data = null, $whiteList = null); + public function setDirtyState(int $dirtyState); /** - * Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception - * Returning true on success or false otherwise. + * Sets the DependencyInjection connection service used to read data * - * @param array $data - * @param array $whiteList - * @return boolean + * @param string $connectionService */ - public function update($data = null, $whiteList = null); + public function setReadConnectionService(string $connectionService); /** - * Deletes a model instance. Returning true on success or false otherwise. + * Sets the record's snapshot data. This method is used internally to set + * snapshot data when the model was set up to keep snapshot data * - * @return boolean + * @param array $data + * @param array $columnMap */ - public function delete(); + public function setSnapshotData(array $data, $columnMap = null); /** - * Returns the type of the latest operation performed by the ORM - * Returns one of the OP_ class constants + * Sets a transaction related to the Model instance * - * @return int + * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @return \Phalcon\Mvc\ModelInterface */ - public function getOperationMade(); + public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction): ModelInterface; /** - * Refreshes the model attributes re-querying the record from the database + * Sets the DependencyInjection connection service used to write data + * + * @param string $connectionService */ - public function refresh(); + public function setWriteConnectionService(string $connectionService); /** * Skips the current operation forcing a success state * * @param bool $skip */ - public function skipOperation($skip); + public function skipOperation(bool $skip); /** - * Returns related records based on defined relations + * Allows to calculate a sum on a column that match the specified conditions * - * @param string $alias - * @param array $arguments - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @param array $parameters + * @return double */ - public function getRelated($alias, $arguments = null); + public static function sum($parameters = null): float; /** - * Sets the record's snapshot data. - * This method is used internally to set snapshot data when the model was set up to keep snapshot data + * Check whether validation process has generated any messages * - * @param array $data - * @param array $columnMap + * @return bool */ - public function setSnapshotData(array $data, $columnMap = null); + public function validationHasFailed(): bool; /** - * Reset a model instance data + * Updates a model instance. If the instance doesn't exist in the + * persistence it will throw an exception. Returning true on success or + * false otherwise. + * + * @return bool */ - public function reset(); + public function update(): bool; } diff --git a/src/Phalcon/mvc/ModuleDefinitionInterface.php b/src/Phalcon/mvc/ModuleDefinitionInterface.php index a1336e4e..fe59a300 100644 --- a/src/Phalcon/mvc/ModuleDefinitionInterface.php +++ b/src/Phalcon/mvc/ModuleDefinitionInterface.php @@ -13,15 +13,15 @@ interface ModuleDefinitionInterface /** * Registers an autoloader related to the module * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function registerAutoloaders(\Phalcon\DiInterface $dependencyInjector = null); + public function registerAutoloaders(\Phalcon\Di\DiInterface $container = null); /** * Registers services related to the module * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function registerServices(\Phalcon\DiInterface $dependencyInjector); + public function registerServices(\Phalcon\Di\DiInterface $container); } diff --git a/src/Phalcon/mvc/Router.php b/src/Phalcon/mvc/Router.php index 69a4e1af..852feabd 100644 --- a/src/Phalcon/mvc/Router.php +++ b/src/Phalcon/mvc/Router.php @@ -6,11 +6,11 @@ * Phalcon\Mvc\Router * * Phalcon\Mvc\Router is the standard framework router. Routing is the - * process of taking a URI endpoint (that part of the URI which comes after the base URL) and - * decomposing it into parameters to determine which module, controller, and - * action of that controller should receive the request + * process of taking a URI endpoint (that part of the URI which comes after the + * base URL) and decomposing it into parameters to determine which module, + * controller, and action of that controller should receive the request * - * + * ```php * use Phalcon\Mvc\Router; * * $router = new Router(); @@ -23,87 +23,83 @@ * ] * ); * - * $router->handle(); + * $router->handle( + * "/documentation/1/examples.html" + * ); * * echo $router->getControllerName(); - * + * ``` */ class Router implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Mvc\RouterInterface, \Phalcon\Events\EventsAwareInterface { - const URI_SOURCE_GET_URL = 0; - - - const URI_SOURCE_SERVER_REQUEST_URI = 1; - - const POSITION_FIRST = 0; const POSITION_LAST = 1; - protected $_dependencyInjector; + protected $action = null; - protected $_eventsManager; + protected $container; - protected $_uriSource; + protected $controller = null; - protected $_namespace = null; + protected $defaultAction; - protected $_module = null; + protected $defaultController; - protected $_controller = null; + protected $defaultModule; - protected $_action = null; + protected $defaultNamespace; - protected $_params = array(); + protected $defaultParams = array(); - protected $_routes; + protected $eventsManager; - protected $_matchedRoute; + protected $keyRouteNames = array(); - protected $_matches; + protected $keyRouteIds = array(); - protected $_wasMatched = false; + protected $matchedRoute; - protected $_defaultNamespace; + protected $matches; - protected $_defaultModule; + protected $module = null; - protected $_defaultController; + protected $namespaceName = null; - protected $_defaultAction; + protected $notFoundPaths; - protected $_defaultParams = array(); + protected $params = array(); - protected $_removeExtraSlashes; + protected $removeExtraSlashes; - protected $_notFoundPaths; + protected $routes; - protected $_keyRouteNames = array(); + protected $uriSource; - protected $_keyRouteIds = array(); + protected $wasMatched = false; @@ -127,141 +123,143 @@ public function setKeyRouteIds($keyRouteIds) {} * * @param bool $defaultRoutes */ - public function __construct($defaultRoutes = true) {} + public function __construct(bool $defaultRoutes = true) {} /** - * Sets the dependency injector + * Adds a route to the router without any HTTP constraint * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the internal dependency injector + * ```php + * use Phalcon\Mvc\Router; * - * @return \Phalcon\DiInterface - */ - public function getDI() {} - - /** - * Sets the events manager + * $router->add("/about", "About::index"); * - * @param \Phalcon\Events\ManagerInterface $eventsManager - */ - public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} - - /** - * Returns the internal event manager + * $router->add( + * "/about", + * "About::index", + * ["GET", "POST"] + * ); * - * @return \Phalcon\Events\ManagerInterface + * $router->add( + * "/about", + * "About::index", + * ["GET", "POST"], + * Router::POSITION_FIRST + * ); + * ``` + * + * @param string $pattern + * @param mixed $paths + * @param mixed $httpMethods + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getEventsManager() {} + public function add(string $pattern, $paths = null, $httpMethods = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read + * Adds a route to the router that only match if the HTTP method is CONNECT * - * @return string + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getRewriteUri() {} + public function addConnect(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets the URI source. One of the URI_SOURCE_ constants - * - * - * $router->setUriSource( - * Router::URI_SOURCE_SERVER_REQUEST_URI - * ); - * + * Adds a route to the router that only match if the HTTP method is DELETE * - * @param mixed $uriSource - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setUriSource($uriSource) {} + public function addDelete(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Set whether router must remove the extra slashes in the handled routes + * Adds a route to the router that only match if the HTTP method is GET * - * @param bool $remove - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function removeExtraSlashes($remove) {} + public function addGet(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets the name of the default namespace + * Adds a route to the router that only match if the HTTP method is HEAD * - * @param string $namespaceName - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaultNamespace($namespaceName) {} + public function addHead(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets the name of the default module + * Add a route to the router that only match if the HTTP method is OPTIONS * - * @param string $moduleName - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaultModule($moduleName) {} + public function addOptions(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets the default controller name + * Adds a route to the router that only match if the HTTP method is PATCH * - * @param string $controllerName - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaultController($controllerName) {} + public function addPatch(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets the default action name + * Adds a route to the router that only match if the HTTP method is POST * - * @param string $actionName - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaultAction($actionName) {} + public function addPost(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Sets an array of default paths. If a route is missing a path the router will use the defined here - * This method must not be used to set a 404 route + * Adds a route to the router that only match if the HTTP method is PURGE + * (Squid and Varnish support) * - * - * $router->setDefaults( - * [ - * "module" => "common", - * "action" => "index", - * ] - * ); - * - * - * @param array $defaults - * @return RouterInterface + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaults(array $defaults) {} + public function addPurge(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Returns an array of default parameters + * Adds a route to the router that only match if the HTTP method is PUT * - * @return array + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getDefaults() {} + public function addPut(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** - * Handles routing information received from the rewrite engine - * - * - * // Read the info from the rewrite engine - * $router->handle(); - * - * // Manually passing an URL - * $router->handle("/posts/edit/1"); - * + * Adds a route to the router that only match if the HTTP method is TRACE * - * @param string $uri + * @param string $pattern + * @param mixed $paths + * @param mixed $position + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function handle($uri = null) {} + public function addTrace(string $pattern, $paths = null, $position = Router::POSITION_LAST): RouteInterface {} /** * Attach Route object to the routes stack. * - * + * ```php * use Phalcon\Mvc\Router; * use Phalcon\Mvc\Router\Route; * @@ -275,239 +273,226 @@ public function handle($uri = null) {} * new CustomRoute("/about", "About::index", ["GET", "HEAD"]), * Router::POSITION_FIRST * ); - * + * ``` * - * @todo Add to the interface for 4.0.0 * @param \Phalcon\Mvc\Router\RouteInterface $route * @param mixed $position * @return RouterInterface */ - public function attach(\Phalcon\Mvc\Router\RouteInterface $route, $position = Router::POSITION_LAST) {} + public function attach(\Phalcon\Mvc\Router\RouteInterface $route, $position = Router::POSITION_LAST): RouterInterface {} /** - * Adds a route to the router without any HTTP constraint - * - * - * use Phalcon\Mvc\Router; - * - * $router->add("/about", "About::index"); - * $router->add("/about", "About::index", ["GET", "POST"]); - * $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); - * + * Removes all the pre-defined routes + */ + public function clear() {} + + /** + * Returns the internal dependency injector * - * @param string $pattern - * @param mixed $paths - * @param mixed $httpMethods - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return \Phalcon\Di\DiInterface */ - public function add($pattern, $paths = null, $httpMethods = null, $position = Router::POSITION_LAST) {} + public function getDI(): DiInterface {} /** - * Adds a route to the router that only match if the HTTP method is GET + * Returns the internal event manager * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return \Phalcon\Events\ManagerInterface */ - public function addGet($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getEventsManager(): ManagerInterface {} /** - * Adds a route to the router that only match if the HTTP method is POST + * Returns the processed action name * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addPost($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getActionName(): string {} /** - * Adds a route to the router that only match if the HTTP method is PUT + * Returns the processed controller name * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addPut($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getControllerName(): string {} /** - * Adds a route to the router that only match if the HTTP method is PATCH + * Returns the route that matches the handled URI * - * @param string $pattern - * @param mixed $paths - * @param mixed $position * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPatch($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getMatchedRoute(): RouteInterface {} /** - * Adds a route to the router that only match if the HTTP method is DELETE + * Returns the sub expressions in the regular expression matched * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return array */ - public function addDelete($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getMatches(): array {} /** - * Add a route to the router that only match if the HTTP method is OPTIONS + * Returns the processed module name * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addOptions($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getModuleName(): string {} /** - * Adds a route to the router that only match if the HTTP method is HEAD + * Returns the processed namespace name * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addHead($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getNamespaceName(): string {} /** - * Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support) + * Returns the processed parameters * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @return array */ - public function addPurge($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getParams(): array {} /** - * Adds a route to the router that only match if the HTTP method is TRACE + * Returns a route object by its id * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @param mixed $id + * @return bool|\Phalcon\Mvc\Router\RouteInterface */ - public function addTrace($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getRouteById($id) {} /** - * Adds a route to the router that only match if the HTTP method is CONNECT + * Returns a route object by its name * - * @param string $pattern - * @param mixed $paths - * @param mixed $position - * @return \Phalcon\Mvc\Router\RouteInterface + * @param string $name + * @return bool|\Phalcon\Mvc\Router\RouteInterface */ - public function addConnect($pattern, $paths = null, $position = Router::POSITION_LAST) {} + public function getRouteByName(string $name) {} /** - * Mounts a group of routes in the router + * Returns all the routes defined in the router * - * @param \Phalcon\Mvc\Router\GroupInterface $group - * @return RouterInterface + * @return array|\Phalcon\Mvc\Router\RouteInterface[] */ - public function mount(\Phalcon\Mvc\Router\GroupInterface $group) {} + public function getRoutes(): array {} /** - * Set a group of paths to be returned when none of the defined routes are matched + * Handles routing information received from the rewrite engine * - * @param mixed $paths - * @return RouterInterface + * ```php + * // Passing a URL + * $router->handle("/posts/edit/1"); + * ``` + * + * @param string $uri */ - public function notFound($paths) {} + public function handle(string $uri) {} /** - * Removes all the pre-defined routes + * Returns whether controller name should not be mangled + * + * @return bool */ - public function clear() {} + public function isExactControllerName(): bool {} /** - * Returns the processed namespace name + * Mounts a group of routes in the router * - * @return string + * @param \Phalcon\Mvc\Router\GroupInterface $group + * @return RouterInterface */ - public function getNamespaceName() {} + public function mount(\Phalcon\Mvc\Router\GroupInterface $group): RouterInterface {} /** - * Returns the processed module name + * Set a group of paths to be returned when none of the defined routes are + * matched * - * @return string + * @param mixed $paths + * @return RouterInterface */ - public function getModuleName() {} + public function notFound($paths): RouterInterface {} /** - * Returns the processed controller name + * Set whether router must remove the extra slashes in the handled routes * - * @return string + * @param bool $remove + * @return RouterInterface */ - public function getControllerName() {} + public function removeExtraSlashes(bool $remove): RouterInterface {} /** - * Returns the processed action name + * Sets the default action name * - * @return string + * @param string $actionName + * @return RouterInterface */ - public function getActionName() {} + public function setDefaultAction(string $actionName): RouterInterface {} /** - * Returns the processed parameters + * Sets the default controller name * - * @return array + * @param string $controllerName + * @return RouterInterface */ - public function getParams() {} + public function setDefaultController(string $controllerName): RouterInterface {} /** - * Returns the route that matches the handled URI + * Sets the name of the default module * - * @return \Phalcon\Mvc\Router\RouteInterface + * @param string $moduleName + * @return RouterInterface */ - public function getMatchedRoute() {} + public function setDefaultModule(string $moduleName): RouterInterface {} /** - * Returns the sub expressions in the regular expression matched + * Sets the name of the default namespace * - * @return array + * @param string $namespaceName + * @return RouterInterface */ - public function getMatches() {} + public function setDefaultNamespace(string $namespaceName): RouterInterface {} /** - * Checks if the router matches any of the defined routes + * Sets an array of default paths. If a route is missing a path the router + * will use the defined here. This method must not be used to set a 404 + * route * - * @return bool + * ```php + * $router->setDefaults( + * [ + * "module" => "common", + * "action" => "index", + * ] + * ); + * ``` + * + * @param array $defaults + * @return RouterInterface */ - public function wasMatched() {} + public function setDefaults(array $defaults): RouterInterface {} /** - * Returns all the routes defined in the router + * Returns an array of default parameters * - * @return \Phalcon\Mvc\Router\RouteInterface[] + * @return array */ - public function getRoutes() {} + public function getDefaults(): array {} /** - * Returns a route object by its id + * Sets the dependency injector * - * @param mixed $id - * @return bool|\Phalcon\Mvc\Router\RouteInterface + * @param \Phalcon\Di\DiInterface $container */ - public function getRouteById($id) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Returns a route object by its name + * Sets the events manager * - * @param string $name - * @return bool|\Phalcon\Mvc\Router\RouteInterface + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function getRouteByName($name) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Returns whether controller name should not be mangled + * Checks if the router matches any of the defined routes * * @return bool */ - public function isExactControllerName() {} + public function wasMatched(): bool {} } diff --git a/src/Phalcon/mvc/RouterInterface.php b/src/Phalcon/mvc/RouterInterface.php index 6f7adef2..f78d3286 100644 --- a/src/Phalcon/mvc/RouterInterface.php +++ b/src/Phalcon/mvc/RouterInterface.php @@ -3,84 +3,74 @@ namespace Phalcon\Mvc; /** - * Phalcon\Mvc\RouterInterface - * * Interface for Phalcon\Mvc\Router */ interface RouterInterface { /** - * Sets the name of the default module - * - * @param string $moduleName - */ - public function setDefaultModule($moduleName); - - /** - * Sets the default controller name - * - * @param string $controllerName - */ - public function setDefaultController($controllerName); - - /** - * Sets the default action name + * Adds a route to the router on any HTTP method * - * @param string $actionName + * @param string $pattern + * @param mixed $paths + * @param mixed $httpMethods + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setDefaultAction($actionName); + public function add(string $pattern, $paths = null, $httpMethods = null): RouteInterface; /** - * Sets an array of default paths + * Attach Route object to the routes stack. * - * @param array $defaults + * @param \Phalcon\Mvc\Router\RouteInterface $route + * @param mixed $position + * @return RouterInterface */ - public function setDefaults(array $defaults); + public function attach(\Phalcon\Mvc\Router\RouteInterface $route, $position = Router::POSITION_LAST): RouterInterface; /** - * Handles routing information received from the rewrite engine + * Adds a route to the router that only match if the HTTP method is CONNECT * - * @param string $uri + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function handle($uri = null); + public function addConnect(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router on any HTTP method + * Adds a route to the router that only match if the HTTP method is DELETE * * @param string $pattern * @param mixed $paths - * @param mixed $httpMethods * @return \Phalcon\Mvc\Router\RouteInterface */ - public function add($pattern, $paths = null, $httpMethods = null); + public function addDelete(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is GET + * Adds a route to the router that only match if the HTTP method is HEAD * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addGet($pattern, $paths = null); + public function addHead(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is POST + * Adds a route to the router that only match if the HTTP method is GET * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPost($pattern, $paths = null); + public function addGet(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is PUT + * Add a route to the router that only match if the HTTP method is OPTIONS * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPut($pattern, $paths = null); + public function addOptions(string $pattern, $paths = null): RouteInterface; /** * Adds a route to the router that only match if the HTTP method is PATCH @@ -89,152 +79,170 @@ public function addPut($pattern, $paths = null); * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPatch($pattern, $paths = null); + public function addPatch(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is DELETE + * Adds a route to the router that only match if the HTTP method is POST * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addDelete($pattern, $paths = null); + public function addPost(string $pattern, $paths = null): RouteInterface; /** - * Add a route to the router that only match if the HTTP method is OPTIONS + * Adds a route to the router that only match if the HTTP method is PURGE + * (Squid and Varnish support) * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addOptions($pattern, $paths = null); + public function addPurge(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is HEAD + * Adds a route to the router that only match if the HTTP method is PUT * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addHead($pattern, $paths = null); + public function addPut(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support) + * Adds a route to the router that only match if the HTTP method is TRACE * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPurge($pattern, $paths = null); + public function addTrace(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is TRACE + * Removes all the defined routes + */ + public function clear(); + + /** + * Returns processed action name * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addTrace($pattern, $paths = null); + public function getActionName(): string; /** - * Adds a route to the router that only match if the HTTP method is CONNECT + * Returns processed controller name * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addConnect($pattern, $paths = null); + public function getControllerName(): string; /** - * Mounts a group of routes in the router + * Returns the route that matches the handled URI * - * @param \Phalcon\Mvc\Router\GroupInterface $group - * @return RouterInterface + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function mount(\Phalcon\Mvc\Router\GroupInterface $group); + public function getMatchedRoute(): RouteInterface; /** - * Removes all the defined routes + * Return the sub expressions in the regular expression matched + * + * @return array */ - public function clear(); + public function getMatches(): array; /** * Returns processed module name * * @return string */ - public function getModuleName(); + public function getModuleName(): string; /** * Returns processed namespace name * * @return string */ - public function getNamespaceName(); + public function getNamespaceName(): string; /** - * Returns processed controller name + * Returns processed extra params * - * @return string + * @return array */ - public function getControllerName(); + public function getParams(): array; /** - * Returns processed action name + * Return all the routes defined in the router * - * @return string + * @return array|\Phalcon\Mvc\Router\RouteInterface[] */ - public function getActionName(); + public function getRoutes(): array; /** - * Returns processed extra params + * Returns a route object by its id * - * @return array + * @param mixed $id + * @return bool|\Phalcon\Mvc\Router\RouteInterface */ - public function getParams(); + public function getRouteById($id); /** - * Returns the route that matches the handled URI + * Returns a route object by its name * - * @return \Phalcon\Mvc\Router\RouteInterface + * @param string $name + * @return bool|\Phalcon\Mvc\Router\RouteInterface */ - public function getMatchedRoute(); + public function getRouteByName(string $name); /** - * Return the sub expressions in the regular expression matched + * Handles routing information received from the rewrite engine * - * @return array + * @param string $uri */ - public function getMatches(); + public function handle(string $uri); /** - * Check if the router matches any of the defined routes + * Mounts a group of routes in the router * - * @return bool + * @param \Phalcon\Mvc\Router\GroupInterface $group + * @return RouterInterface */ - public function wasMatched(); + public function mount(\Phalcon\Mvc\Router\GroupInterface $group): RouterInterface; /** - * Return all the routes defined in the router + * Sets the default action name * - * @return \Phalcon\Mvc\Router\RouteInterface[] + * @param string $actionName */ - public function getRoutes(); + public function setDefaultAction(string $actionName); /** - * Returns a route object by its id + * Sets the default controller name * - * @param mixed $id - * @return bool|\Phalcon\Mvc\Router\RouteInterface + * @param string $controllerName */ - public function getRouteById($id); + public function setDefaultController(string $controllerName); /** - * Returns a route object by its name + * Sets the name of the default module * - * @param string $name - * @return bool|\Phalcon\Mvc\Router\RouteInterface + * @param string $moduleName + */ + public function setDefaultModule(string $moduleName); + + /** + * Sets an array of default paths + * + * @param array $defaults + */ + public function setDefaults(array $defaults); + + /** + * Check if the router matches any of the defined routes + * + * @return bool */ - public function getRouteByName($name); + public function wasMatched(): bool; } diff --git a/src/Phalcon/mvc/Url.php b/src/Phalcon/mvc/Url.php deleted file mode 100644 index 92b6e69a..00000000 --- a/src/Phalcon/mvc/Url.php +++ /dev/null @@ -1,184 +0,0 @@ - - * // Generate a URL appending the URI to the base URI - * echo $url->get("products/edit/1"); - * - * // Generate a URL for a predefined route - * echo $url->get( - * [ - * "for" => "blog-post", - * "title" => "some-cool-stuff", - * "year" => "2012", - * ] - * ); - * - */ -class Url implements \Phalcon\Mvc\UrlInterface, \Phalcon\Di\InjectionAwareInterface -{ - - protected $_dependencyInjector; - - - protected $_baseUri = null; - - - protected $_staticBaseUri = null; - - - protected $_basePath = null; - - - protected $_router; - - - /** - * Sets the DependencyInjector container - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the DependencyInjector container - * - * @return \Phalcon\DiInterface - */ - public function getDI() {} - - /** - * Sets a prefix for all the URIs to be generated - * - * - * $url->setBaseUri("/invo/"); - * - * $url->setBaseUri("/invo/index.php/"); - * - * - * @param string $baseUri - * @return Url - */ - public function setBaseUri($baseUri) {} - - /** - * Sets a prefix for all static URLs generated - * - * - * $url->setStaticBaseUri("/invo/"); - * - * - * @param string $staticBaseUri - * @return Url - */ - public function setStaticBaseUri($staticBaseUri) {} - - /** - * Returns the prefix for all the generated urls. By default / - * - * @return string - */ - public function getBaseUri() {} - - /** - * Returns the prefix for all the generated static urls. By default / - * - * @return string - */ - public function getStaticBaseUri() {} - - /** - * Sets a base path for all the generated paths - * - * - * $url->setBasePath("/var/www/htdocs/"); - * - * - * @param string $basePath - * @return Url - */ - public function setBasePath($basePath) {} - - /** - * Returns the base path - * - * @return string - */ - public function getBasePath() {} - - /** - * Generates a URL - * - * - * // Generate a URL appending the URI to the base URI - * echo $url->get("products/edit/1"); - * - * // Generate a URL for a predefined route - * echo $url->get( - * [ - * "for" => "blog-post", - * "title" => "some-cool-stuff", - * "year" => "2015", - * ] - * ); - * - * // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - * echo $url->get( - * "show/products", - * [ - * "id" => 1, - * "name" => "Carrots", - * ] - * ); - * - * // Generate an absolute URL by setting the third parameter as false. - * echo $url->get( - * "https://phalconphp.com/", - * null, - * false - * ); - * - * - * @param mixed $uri - * @param mixed $args - * @param mixed $local - * @param mixed $baseUri - * @return string - */ - public function get($uri = null, $args = null, $local = null, $baseUri = null) {} - - /** - * Generates a URL for a static resource - * - * - * // Generate a URL for a static resource - * echo $url->getStatic("img/logo.png"); - * - * // Generate a URL for a static predefined route - * echo $url->getStatic( - * [ - * "for" => "logo-cdn", - * ] - * ); - * - * - * @param mixed $uri - * @return string - */ - public function getStatic($uri = null) {} - - /** - * Generates a local path - * - * @param string $path - * @return string - */ - public function path($path = null) {} - -} diff --git a/src/Phalcon/mvc/View.php b/src/Phalcon/mvc/View.php index f55dcfd4..e8270a85 100644 --- a/src/Phalcon/mvc/View.php +++ b/src/Phalcon/mvc/View.php @@ -5,11 +5,12 @@ /** * Phalcon\Mvc\View * - * Phalcon\Mvc\View is a class for working with the "view" portion of the model-view-controller pattern. - * That is, it exists to help keep the view script separate from the model and controller scripts. - * It provides a system of helpers, output filters, and variable escaping. + * Phalcon\Mvc\View is a class for working with the "view" portion of the + * model-view-controller pattern. That is, it exists to help keep the view + * script separate from the model and controller scripts. It provides a system + * of helpers, output filters, and variable escaping. * - * + * ```php * use Phalcon\Mvc\View; * * $view = new View(); @@ -25,19 +26,19 @@ * * // Printing views output * echo $view->getContent(); - * + * ``` */ class View extends \Phalcon\Di\Injectable implements \Phalcon\Mvc\ViewInterface { /** - * Render Level: To the main layout + * Render Level: To the action view */ - const LEVEL_MAIN_LAYOUT = 5; + const LEVEL_ACTION_VIEW = 1; /** - * Render Level: Render to the templates "after" + * Render Level: To the templates "before" */ - const LEVEL_AFTER_TEMPLATE = 4; + const LEVEL_BEFORE_TEMPLATE = 2; /** * Render Level: To the controller layout @@ -45,14 +46,9 @@ class View extends \Phalcon\Di\Injectable implements \Phalcon\Mvc\ViewInterface const LEVEL_LAYOUT = 3; /** - * Render Level: To the templates "before" - */ - const LEVEL_BEFORE_TEMPLATE = 2; - - /** - * Render Level: To the action view + * Render Level: To the main layout */ - const LEVEL_ACTION_VIEW = 1; + const LEVEL_MAIN_LAYOUT = 5; /** * Render Level: No render any view @@ -60,99 +56,86 @@ class View extends \Phalcon\Di\Injectable implements \Phalcon\Mvc\ViewInterface const LEVEL_NO_RENDER = 0; /** - * Cache Mode + * Render Level: Render to the templates "after" */ - const CACHE_MODE_NONE = 0; - + const LEVEL_AFTER_TEMPLATE = 4; - const CACHE_MODE_INVERSE = 1; + protected $actionName; - protected $_options; + protected $activeRenderPaths; - protected $_basePath = ''; + protected $basePath = ''; - protected $_content = ''; + protected $content = ''; - protected $_renderLevel = 5; + protected $controllerName; - protected $_currentRenderLevel = 0; + protected $currentRenderLevel = 0; - protected $_disabledLevels; + protected $disabled = false; - protected $_viewParams = array(); + protected $disabledLevels; - protected $_layout; + protected $engines = false; - protected $_layoutsDir = ''; + protected $layout; - protected $_partialsDir = ''; + protected $layoutsDir = ''; - protected $_viewsDirs = array(); + protected $mainView = 'index'; - protected $_templatesBefore = array(); + protected $options = array(); - protected $_templatesAfter = array(); + protected $params; - protected $_engines = false; - /** - * @var array - */ - protected $_registeredEngines; + protected $pickView; - protected $_mainView = 'index'; + protected $partialsDir = ''; - protected $_controllerName; + protected $registeredEngines = array(); - protected $_actionName; + protected $renderLevel = 5; - protected $_params; + protected $templatesAfter = array(); - protected $_pickView; + protected $templatesBefore = array(); - protected $_cache; + protected $viewsDirs = array(); - protected $_cacheLevel = 0; + protected $viewParams = array(); - protected $_activeRenderPaths; + public function getCurrentRenderLevel() {} - protected $_disabled = false; + public function getRegisteredEngines() {} public function getRenderLevel() {} - - public function getCurrentRenderLevel() {} - - /** - * @return array - */ - public function getRegisteredEngines() {} - /** * Phalcon\Mvc\View constructor * @@ -161,563 +144,542 @@ public function getRegisteredEngines() {} public function __construct(array $options = array()) {} /** - * Checks if a path is absolute or not + * Magic method to retrieve a variable passed to the view * - * @param string $path + * ```php + * echo $this->view->products; + * ``` + * + * @param string $key + * @return mixed|null */ - protected final function _isAbsolutePath($path) {} + public function __get(string $key): ? {} /** - * Sets the views directory. Depending of your platform, - * always add a trailing slash or backslash + * Magic method to retrieve if a variable is set in the view * - * @param mixed $viewsDir - * @return View + * ```php + * echo isset($this->view->products); + * ``` + * + * @param string $key + * @return bool */ - public function setViewsDir($viewsDir) {} + public function __isset(string $key): bool {} /** - * Gets views directory + * Magic method to pass variables to the views * - * @return string|array + * ```php + * $this->view->products = $products; + * ``` + * + * @param string $key + * @param mixed $value */ - public function getViewsDir() {} + public function __set(string $key, $value) {} /** - * Sets the layouts sub-directory. Must be a directory under the views directory. - * Depending of your platform, always add a trailing slash or backslash - * - * - * $view->setLayoutsDir("../common/layouts/"); - * + * Resets any template before layouts * - * @param string $layoutsDir * @return View */ - public function setLayoutsDir($layoutsDir) {} + public function cleanTemplateAfter(): View {} /** - * Gets the current layouts sub-directory + * Resets any "template before" layouts * - * @return string + * @return View */ - public function getLayoutsDir() {} + public function cleanTemplateBefore(): View {} /** - * Sets a partials sub-directory. Must be a directory under the views directory. - * Depending of your platform, always add a trailing slash or backslash + * Disables a specific level of rendering * - * - * $view->setPartialsDir("../common/partials/"); - * + * ```php + * // Render all levels except ACTION level + * $this->view->disableLevel( + * View::LEVEL_ACTION_VIEW + * ); + * ``` * - * @param string $partialsDir - * @return View + * @param mixed $level + * @return \Phalcon\Mvc\ViewInterface */ - public function setPartialsDir($partialsDir) {} + public function disableLevel($level): ViewInterface {} /** - * Gets the current partials sub-directory + * Disables the auto-rendering process * - * @return string + * @return View */ - public function getPartialsDir() {} + public function disable(): View {} /** - * Sets base path. Depending of your platform, always add a trailing slash or backslash - * - * - * $view->setBasePath(__DIR__ . "/"); - * + * Enables the auto-rendering process * - * @param string $basePath * @return View */ - public function setBasePath($basePath) {} + public function enable(): View {} /** - * Gets base path + * Checks whether view exists * - * @return string + * @param string $view + * @return bool */ - public function getBasePath() {} + public function exists(string $view): bool {} /** - * Sets the render level for the view - * - * - * // Render the view related to the controller only - * $this->view->setRenderLevel( - * View::LEVEL_LAYOUT - * ); - * + * Finishes the render process by stopping the output buffering * - * @param int $level * @return View */ - public function setRenderLevel($level) {} + public function finish(): View {} /** - * Disables a specific level of rendering - * - * - * // Render all levels except ACTION level - * $this->view->disableLevel( - * View::LEVEL_ACTION_VIEW - * ); - * + * Gets the name of the action rendered * - * @param mixed $level - * @return View + * @return string */ - public function disableLevel($level) {} + public function getActionName(): string {} /** - * Sets default view name. Must be a file without extension in the views directory - * - * - * // Renders as main view views-dir/base.phtml - * $this->view->setMainView("base"); - * + * Returns the path (or paths) of the views that are currently rendered * - * @param string $viewPath - * @return View + * @return string|array */ - public function setMainView($viewPath) {} + public function getActiveRenderPath() {} /** - * Returns the name of the main view + * Gets base path * * @return string */ - public function getMainView() {} + public function getBasePath(): string {} /** - * Change the layout to be used instead of using the name of the latest controller name + * Returns output from another view stage * - * - * $this->view->setLayout("main"); - * + * @return string + */ + public function getContent(): string {} + + /** + * Gets the name of the controller rendered * - * @param string $layout - * @return View + * @return string */ - public function setLayout($layout) {} + public function getControllerName(): string {} /** * Returns the name of the main view * * @return string */ - public function getLayout() {} + public function getLayout(): string {} /** - * Sets a template before the controller layout + * Gets the current layouts sub-directory * - * @param mixed $templateBefore - * @return View + * @return string */ - public function setTemplateBefore($templateBefore) {} + public function getLayoutsDir(): string {} /** - * Resets any "template before" layouts + * Returns the name of the main view * - * @return View + * @return string */ - public function cleanTemplateBefore() {} + public function getMainView(): string {} /** - * Sets a "template after" controller layout + * Returns parameters to views * - * @param mixed $templateAfter - * @return View + * @return array */ - public function setTemplateAfter($templateAfter) {} + public function getParamsToView(): array {} /** - * Resets any template before layouts + * Renders a partial view * - * @return View + * ```php + * // Retrieve the contents of a partial + * echo $this->getPartial("shared/footer"); + * ``` + * + * ```php + * // Retrieve the contents of a partial with arguments + * echo $this->getPartial( + * "shared/footer", + * [ + * "content" => $html, + * ] + * ); + * ``` + * + * @param string $partialPath + * @param mixed $params + * @return string */ - public function cleanTemplateAfter() {} + public function getPartial(string $partialPath, $params = null): string {} /** - * Adds parameters to views (alias of setVar) - * - * - * $this->view->setParamToView("products", $products); - * + * Gets the current partials sub-directory * - * @param string $key - * @param mixed $value - * @return View + * @return string */ - public function setParamToView($key, $value) {} + public function getPartialsDir(): string {} /** - * Set all the render params + * Perform the automatic rendering returning the output as a string * - * - * $this->view->setVars( + * ```php + * $template = $this->view->getRender( + * "products", + * "show", * [ * "products" => $products, * ] * ); - * + * ``` * + * @param string $controllerName + * @param string $actionName * @param array $params - * @param bool $merge - * @return View + * @param mixed $configCallback + * @return string */ - public function setVars(array $params, $merge = true) {} + public function getRender(string $controllerName, string $actionName, array $params = array(), $configCallback = null): string {} /** - * Set a single view parameter - * - * - * $this->view->setVar("products", $products); - * + * Returns a parameter previously set in the view * * @param string $key - * @param mixed $value - * @return View */ - public function setVar($key, $value) {} + public function getVar(string $key) {} /** - * Returns a parameter previously set in the view + * Gets views directory * - * @param string $key + * @return string|array */ - public function getVar($key) {} + public function getViewsDir() {} /** - * Returns parameters to views + * Gets views directories * * @return array */ - public function getParamsToView() {} + protected function getViewsDirs(): array {} /** - * Gets the name of the controller rendered + * Whether automatic rendering is enabled * - * @return string + * @return bool */ - public function getControllerName() {} + public function isDisabled(): bool {} /** - * Gets the name of the action rendered + * Renders a partial view * - * @return string - */ - public function getActionName() {} - - /** - * Gets extra parameters of the action rendered + * ```php + * // Show a partial inside another view + * $this->partial("shared/footer"); + * ``` * - * @deprecated Will be removed in 4.0.0 - * @deprecated - * @return array - */ - public function getParams() {} - - /** - * Starts rendering process enabling the output buffering + * ```php + * // Show a partial inside another view with parameters + * $this->partial( + * "shared/footer", + * [ + * "content" => $html, + * ] + * ); + * ``` * - * @return View + * @param string $partialPath + * @param mixed $params */ - public function start() {} + public function partial(string $partialPath, $params = null) {} /** - * Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php + * Choose a different view to render instead of last-controller/last-action * - * @return array - */ - protected function _loadTemplateEngines() {} - - /** - * Checks whether view exists on registered extensions and render it + * ```php + * use Phalcon\Mvc\Controller; * - * @param array $engines - * @param string $viewPath - * @param boolean $silence - * @param boolean $mustClean - * @param \Phalcon\Cache\BackendInterface $cache + * class ProductsController extends Controller + * { + * public function saveAction() + * { + * // Do some save stuff... + * + * // Then show the list view + * $this->view->pick("products/list"); + * } + * } + * ``` + * + * @param mixed $renderView + * @return View */ - protected function _engineRender($engines, $viewPath, $silence, $mustClean, \Phalcon\Cache\BackendInterface $cache = null) {} + public function pick($renderView): View {} /** * Register templating engines * - * + * ```php * $this->view->registerEngines( * [ - * ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", - * ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", - * ".mhtml" => "MyCustomEngine", + * ".phtml" => \Phalcon\Mvc\View\Engine\Php::class, + * ".volt" => \Phalcon\Mvc\View\Engine\Volt::class, + * ".mhtml" => \MyCustomEngine::class, * ] * ); - * + * ``` * * @param array $engines * @return View */ - public function registerEngines(array $engines) {} - - /** - * Checks whether view exists - * - * @param string $view - * @return bool - */ - public function exists($view) {} + public function registerEngines(array $engines): View {} /** * Executes render process from dispatching data * - * + * ```php * // Shows recent posts view (app/views/posts/recent.phtml) * $view->start()->render("posts", "recent")->finish(); - * + * ``` * * @param string $controllerName * @param string $actionName * @param array $params * @return bool|View */ - public function render($controllerName, $actionName, $params = null) {} + public function render(string $controllerName, string $actionName, array $params = array()) {} /** - * Choose a different view to render instead of last-controller/last-action - * - * - * use Phalcon\Mvc\Controller; - * - * class ProductsController extends Controller - * { - * public function saveAction() - * { - * // Do some save stuff... - * - * // Then show the list view - * $this->view->pick("products/list"); - * } - * } - * + * Resets the view component to its factory default values * - * @param mixed $renderView * @return View */ - public function pick($renderView) {} + public function reset(): View {} /** - * Renders a partial view + * Sets base path. Depending of your platform, always add a trailing slash + * or backslash * - * - * // Retrieve the contents of a partial - * echo $this->getPartial("shared/footer"); - * + * ```php + * $view->setBasePath(__DIR__ . "/"); + * ``` * - * - * // Retrieve the contents of a partial with arguments - * echo $this->getPartial( - * "shared/footer", - * [ - * "content" => $html, - * ] - * ); - * - * - * @param string $partialPath - * @param mixed $params - * @return string + * @param string $basePath + * @return View */ - public function getPartial($partialPath, $params = null) {} + public function setBasePath(string $basePath): View {} /** - * Renders a partial view - * - * - * // Show a partial inside another view - * $this->partial("shared/footer"); - * + * Externally sets the view content * - * - * // Show a partial inside another view with parameters - * $this->partial( - * "shared/footer", - * [ - * "content" => $html, - * ] - * ); - * + * ```php + * $this->view->setContent("

hello

"); + * ``` * - * @param string $partialPath - * @param mixed $params + * @param string $content + * @return View */ - public function partial($partialPath, $params = null) {} + public function setContent(string $content): View {} /** - * Perform the automatic rendering returning the output as a string + * Change the layout to be used instead of using the name of the latest + * controller name * - * - * $template = $this->view->getRender( - * "products", - * "show", - * [ - * "products" => $products, - * ] - * ); - * + * ```php + * $this->view->setLayout("main"); + * ``` * - * @param string $controllerName - * @param string $actionName - * @param array $params - * @param mixed $configCallback - * @return string + * @param string $layout + * @return View */ - public function getRender($controllerName, $actionName, $params = null, $configCallback = null) {} + public function setLayout(string $layout): View {} /** - * Finishes the render process by stopping the output buffering + * Sets the layouts sub-directory. Must be a directory under the views + * directory. Depending of your platform, always add a trailing slash or + * backslash * + * ```php + * $view->setLayoutsDir("../common/layouts/"); + * ``` + * + * @param string $layoutsDir * @return View */ - public function finish() {} + public function setLayoutsDir(string $layoutsDir): View {} /** - * Create a Phalcon\Cache based on the internal cache options + * Sets default view name. Must be a file without extension in the views + * directory * - * @return \Phalcon\Cache\BackendInterface + * ```php + * // Renders as main view views-dir/base.phtml + * $this->view->setMainView("base"); + * ``` + * + * @param string $viewPath + * @return View */ - protected function _createCache() {} + public function setMainView(string $viewPath): View {} /** - * Check if the component is currently caching the output content + * Sets a partials sub-directory. Must be a directory under the views + * directory. Depending of your platform, always add a trailing slash or + * backslash * - * @return bool + * ```php + * $view->setPartialsDir("../common/partials/"); + * ``` + * + * @param string $partialsDir + * @return View */ - public function isCaching() {} + public function setPartialsDir(string $partialsDir): View {} /** - * Returns the cache instance used to cache + * Adds parameters to views (alias of setVar) + * + * ```php + * $this->view->setParamToView("products", $products); + * ``` * - * @return \Phalcon\Cache\BackendInterface + * @param string $key + * @param mixed $value + * @return View */ - public function getCache() {} + public function setParamToView(string $key, $value): View {} /** - * Cache the actual view render to certain level + * Sets the render level for the view * - * - * $this->view->cache( - * [ - * "key" => "my-key", - * "lifetime" => 86400, - * ] + * ```php + * // Render the view related to the controller only + * $this->view->setRenderLevel( + * View::LEVEL_LAYOUT * ); - * + * ``` * - * @param mixed $options - * @return View + * @param int $level + * @return \Phalcon\Mvc\ViewInterface */ - public function cache($options = true) {} + public function setRenderLevel(int $level): ViewInterface {} /** - * Externally sets the view content - * - * - * $this->view->setContent("

hello

"); - *
+ * Sets a "template after" controller layout * - * @param string $content + * @param mixed $templateAfter * @return View */ - public function setContent($content) {} + public function setTemplateAfter($templateAfter): View {} /** - * Returns cached output from another view stage + * Sets a template before the controller layout * - * @return string + * @param mixed $templateBefore + * @return View */ - public function getContent() {} + public function setTemplateBefore($templateBefore): View {} /** - * Returns the path (or paths) of the views that are currently rendered + * Set a single view parameter * - * @return string|array + * ```php + * $this->view->setVar("products", $products); + * ``` + * + * @param string $key + * @param mixed $value + * @return View */ - public function getActiveRenderPath() {} + public function setVar(string $key, $value): View {} /** - * Disables the auto-rendering process + * Set all the render params * + * ```php + * $this->view->setVars( + * [ + * "products" => $products, + * ] + * ); + * ``` + * + * @param array $params + * @param bool $merge * @return View */ - public function disable() {} + public function setVars(array $params, bool $merge = true): View {} /** - * Enables the auto-rendering process + * Sets the views directory. Depending of your platform, + * always add a trailing slash or backslash * + * @param mixed $viewsDir * @return View */ - public function enable() {} + public function setViewsDir($viewsDir): View {} /** - * Resets the view component to its factory default values + * Starts rendering process enabling the output buffering * * @return View */ - public function reset() {} + public function start(): View {} /** - * Magic method to pass variables to the views - * - * - * $this->view->products = $products; - * + * Renders the view and returns it as a string * - * @param string $key - * @param mixed $value + * @param string $controllerName + * @param string $actionName + * @param array $params + * @return string */ - public function __set($key, $value) {} + public function toString(string $controllerName, string $actionName, array $params = array()): string {} /** - * Magic method to retrieve a variable passed to the view - * - * - * echo $this->view->products; - * + * Checks whether view exists on registered extensions and render it * - * @param string $key - * @return mixed|null + * @param array $engines + * @param string $viewPath + * @param bool $silence + * @param bool $mustClean */ - public function __get($key) {} + protected function engineRender(array $engines, string $viewPath, bool $silence, bool $mustClean = true) {} /** - * Whether automatic rendering is enabled + * Checks if a path is absolute or not * - * @return bool + * @param string $path */ - public function isDisabled() {} + final protected function isAbsolutePath(string $path) {} /** - * Magic method to retrieve if a variable is set in the view - * - * - * echo isset($this->view->products); - * + * Loads registered template engines, if none is registered it will use + * Phalcon\Mvc\View\Engine\Php * - * @param string $key - * @return bool + * @return array */ - public function __isset($key) {} + protected function loadTemplateEngines(): array {} /** - * Gets views directories + * Processes the view and templates; Fires events if needed * - * @return array + * @param string $controllerName + * @param string $actionName + * @param array $params + * @param bool $fireEvents + * @return bool */ - protected function getViewsDirs() {} + public function processRender(string $controllerName, string $actionName, array $params = array(), bool $fireEvents = true): bool {} } diff --git a/src/Phalcon/mvc/ViewBaseInterface.php b/src/Phalcon/mvc/ViewBaseInterface.php index d0821d61..a88fca68 100644 --- a/src/Phalcon/mvc/ViewBaseInterface.php +++ b/src/Phalcon/mvc/ViewBaseInterface.php @@ -11,76 +11,63 @@ interface ViewBaseInterface { /** - * Sets views directory. Depending of your platform, always add a trailing slash or backslash - * - * @param string $viewsDir - */ - public function setViewsDir($viewsDir); - - /** - * Gets views directory - * - * @return string|array - */ - public function getViewsDir(); - - /** - * Adds parameters to views (alias of setVar) - * - * @param string $key - * @param mixed $value - */ - public function setParamToView($key, $value); - - /** - * Adds parameters to views + * Returns cached output from another view stage * - * @param string $key - * @param mixed $value + * @return string */ - public function setVar($key, $value); + public function getContent(): string; /** * Returns parameters to views * * @return array */ - public function getParamsToView(); + public function getParamsToView(): array; /** - * Returns the cache instance used to cache + * Gets views directory * - * @return \Phalcon\Cache\BackendInterface + * @return string|array */ - public function getCache(); + public function getViewsDir(); /** - * Cache the actual view render to certain level + * Renders a partial view * - * @param mixed $options + * @param string $partialPath + * @param mixed $params */ - public function cache($options = true); + public function partial(string $partialPath, $params = null); /** * Externally sets the view content * * @param string $content */ - public function setContent($content); + public function setContent(string $content); /** - * Returns cached output from another view stage + * Adds parameters to views (alias of setVar) * - * @return string + * @param string $key + * @param mixed $value */ - public function getContent(); + public function setParamToView(string $key, $value); /** - * Renders a partial view + * Adds parameters to views * - * @param string $partialPath - * @param mixed $params + * @param string $key + * @param mixed $value + */ + public function setVar(string $key, $value); + + /** + * Sets views directory. Depending of your platform, always add a trailing + * slash or backslash + * + * @param string $viewsDir */ - public function partial($partialPath, $params = null); + public function setViewsDir(string $viewsDir); } diff --git a/src/Phalcon/mvc/ViewInterface.php b/src/Phalcon/mvc/ViewInterface.php index fb0b5082..c27c5ca3 100644 --- a/src/Phalcon/mvc/ViewInterface.php +++ b/src/Phalcon/mvc/ViewInterface.php @@ -11,135 +11,99 @@ interface ViewInterface extends \Phalcon\Mvc\ViewBaseInterface { /** - * Sets the layouts sub-directory. Must be a directory under the views - * directory. Depending of your platform, always add a trailing slash or backslash - * - * @param string $layoutsDir + * Resets any template before layouts */ - public function setLayoutsDir($layoutsDir); + public function cleanTemplateAfter(); /** - * Gets the current layouts sub-directory - * - * @return string + * Resets any template before layouts */ - public function getLayoutsDir(); + public function cleanTemplateBefore(); /** - * Sets a partials sub-directory. Must be a directory under the views - * directory. Depending of your platform, always add a trailing slash or backslash - * - * @param string $partialsDir + * Disables the auto-rendering process */ - public function setPartialsDir($partialsDir); + public function disable(); /** - * Gets the current partials sub-directory - * - * @return string + * Enables the auto-rendering process */ - public function getPartialsDir(); + public function enable(); /** - * Sets base path. Depending of your platform, always add a trailing slash or backslash - * - * @param string $basePath + * Finishes the render process by stopping the output buffering */ - public function setBasePath($basePath); + public function finish(); /** - * Gets base path + * Gets the name of the action rendered * * @return string */ - public function getBasePath(); + public function getActionName(): string; /** - * Sets the render level for the view - * - * @param int $level - */ - public function setRenderLevel($level); - - /** - * Sets default view name. Must be a file without extension in the views directory + * Returns the path of the view that is currently rendered * - * @param string $viewPath + * @return string|array */ - public function setMainView($viewPath); + public function getActiveRenderPath(); /** - * Returns the name of the main view + * Gets base path * * @return string */ - public function getMainView(); + public function getBasePath(): string; /** - * Change the layout to be used instead of using the name of the latest controller name + * Gets the name of the controller rendered * - * @param string $layout + * @return string */ - public function setLayout($layout); + public function getControllerName(): string; /** * Returns the name of the main view * * @return string */ - public function getLayout(); - - /** - * Appends template before controller layout - * - * @param string|array $templateBefore - */ - public function setTemplateBefore($templateBefore); - - /** - * Resets any template before layouts - */ - public function cleanTemplateBefore(); + public function getLayout(): string; /** - * Appends template after controller layout + * Gets the current layouts sub-directory * - * @param string|array $templateAfter - */ - public function setTemplateAfter($templateAfter); - - /** - * Resets any template before layouts + * @return string */ - public function cleanTemplateAfter(); + public function getLayoutsDir(): string; /** - * Gets the name of the controller rendered + * Returns the name of the main view * * @return string */ - public function getControllerName(); + public function getMainView(): string; /** - * Gets the name of the action rendered + * Gets the current partials sub-directory * * @return string */ - public function getActionName(); + public function getPartialsDir(): string; /** - * Gets extra parameters of the action rendered + * Whether the automatic rendering is disabled * - * @deprecated Will be removed in 4.0.0 - * @deprecated - * @return array + * @return bool */ - public function getParams(); + public function isDisabled(): bool; /** - * Starts rendering process enabling the output buffering + * Choose a view different to render than last-controller/last-action + * + * @param string $renderView */ - public function start(); + public function pick(string $renderView); /** * Register templating engines @@ -154,48 +118,82 @@ public function registerEngines(array $engines); * @param string $controllerName * @param string $actionName * @param array $params + * @return bool|ViewInterface */ - public function render($controllerName, $actionName, $params = null); + public function render(string $controllerName, string $actionName, array $params = array()); /** - * Choose a view different to render than last-controller/last-action + * Resets the view component to its factory default values + */ + public function reset(); + + /** + * Sets base path. Depending of your platform, always add a trailing slash + * or backslash * - * @param string $renderView + * @param string $basePath */ - public function pick($renderView); + public function setBasePath(string $basePath); /** - * Finishes the render process by stopping the output buffering + * Change the layout to be used instead of using the name of the latest + * controller name + * + * @param string $layout */ - public function finish(); + public function setLayout(string $layout); /** - * Returns the path of the view that is currently rendered + * Sets the layouts sub-directory. Must be a directory under the views + * directory. Depending of your platform, always add a trailing slash or + * backslash * - * @return string|array + * @param string $layoutsDir */ - public function getActiveRenderPath(); + public function setLayoutsDir(string $layoutsDir); /** - * Disables the auto-rendering process + * Sets default view name. Must be a file without extension in the views + * directory + * + * @param string $viewPath */ - public function disable(); + public function setMainView(string $viewPath); /** - * Enables the auto-rendering process + * Sets a partials sub-directory. Must be a directory under the views + * directory. Depending of your platform, always add a trailing slash or + * backslash + * + * @param string $partialsDir */ - public function enable(); + public function setPartialsDir(string $partialsDir); /** - * Resets the view component to its factory default values + * Sets the render level for the view + * + * @param int $level + * @return ViewInterface */ - public function reset(); + public function setRenderLevel(int $level): ViewInterface; /** - * Whether the automatic rendering is disabled + * Appends template after controller layout * - * @return bool + * @param string|array $templateAfter */ - public function isDisabled(); + public function setTemplateAfter($templateAfter); + + /** + * Appends template before controller layout + * + * @param string|array $templateBefore + */ + public function setTemplateBefore($templateBefore); + + /** + * Starts rendering process enabling the output buffering + */ + public function start(); } diff --git a/src/Phalcon/mvc/collection/Behavior.php b/src/Phalcon/mvc/collection/Behavior.php index 7ad66958..b0683096 100644 --- a/src/Phalcon/mvc/collection/Behavior.php +++ b/src/Phalcon/mvc/collection/Behavior.php @@ -10,7 +10,7 @@ abstract class Behavior implements \Phalcon\Mvc\Collection\BehaviorInterface { - protected $_options; + protected $options; /** @@ -18,39 +18,39 @@ abstract class Behavior implements \Phalcon\Mvc\Collection\BehaviorInterface * * @param array $options */ - public function __construct($options = null) {} + public function __construct(array $options = array()) {} /** - * Checks whether the behavior must take action on certain event + * Returns the behavior options related to an event * * @param string $eventName - * @return bool + * @return array */ - protected function mustTakeAction($eventName) {} + protected function getOptions(string $eventName = null) {} /** - * Returns the behavior options related to an event + * Acts as fallbacks when a missing method is called on the collection * - * @param string $eventName - * @return array + * @param \Phalcon\Mvc\CollectionInterface $model + * @param string $method + * @param array $arguments */ - protected function getOptions($eventName = null) {} + public function missingMethod(\Phalcon\Mvc\CollectionInterface $model, string $method, array $arguments = array()) {} /** - * This method receives the notifications from the EventsManager + * Checks whether the behavior must take action on certain event * - * @param string $type - * @param \Phalcon\Mvc\CollectionInterface $model + * @param string $eventName + * @return bool */ - public function notify($type, \Phalcon\Mvc\CollectionInterface $model) {} + protected function mustTakeAction(string $eventName): bool {} /** - * Acts as fallbacks when a missing method is called on the collection + * This method receives the notifications from the EventsManager * + * @param string $type * @param \Phalcon\Mvc\CollectionInterface $model - * @param string $method - * @param mixed $arguments */ - public function missingMethod(\Phalcon\Mvc\CollectionInterface $model, $method, $arguments = null) {} + public function notify(string $type, \Phalcon\Mvc\CollectionInterface $model) {} } diff --git a/src/Phalcon/mvc/collection/BehaviorInterface.php b/src/Phalcon/mvc/collection/BehaviorInterface.php index a3d877ba..0a5b1437 100644 --- a/src/Phalcon/mvc/collection/BehaviorInterface.php +++ b/src/Phalcon/mvc/collection/BehaviorInterface.php @@ -11,20 +11,20 @@ interface BehaviorInterface { /** - * This method receives the notifications from the EventsManager + * Calls a method when it's missing in the collection * - * @param string $type * @param \Phalcon\Mvc\CollectionInterface $collection + * @param string $method + * @param array $arguments */ - public function notify($type, \Phalcon\Mvc\CollectionInterface $collection); + public function missingMethod(\Phalcon\Mvc\CollectionInterface $collection, string $method, array $arguments = array()); /** - * Calls a method when it's missing in the collection + * This method receives the notifications from the EventsManager * + * @param string $type * @param \Phalcon\Mvc\CollectionInterface $collection - * @param string $method - * @param mixed $arguments */ - public function missingMethod(\Phalcon\Mvc\CollectionInterface $collection, $method, $arguments = null); + public function notify(string $type, \Phalcon\Mvc\CollectionInterface $collection); } diff --git a/src/Phalcon/mvc/collection/Document.php b/src/Phalcon/mvc/collection/Document.php index bbc95b98..94efc018 100644 --- a/src/Phalcon/mvc/collection/Document.php +++ b/src/Phalcon/mvc/collection/Document.php @@ -12,19 +12,20 @@ class Document implements \Phalcon\Mvc\EntityInterface, \ArrayAccess { /** - * Checks whether an offset exists in the document + * Returns the value of a field using the ArrayAccess interfase * - * @param int $index - * @return bool + * @param mixed $index + * @return mixed */ - public function offsetExists($index) {} + public function offsetGet($index) {} /** - * Returns the value of a field using the ArrayAccess interfase + * Checks whether an offset exists in the document * * @param mixed $index + * @return bool */ - public function offsetGet($index) {} + public function offsetExists($index): bool {} /** * Change a value using the ArrayAccess interface @@ -37,39 +38,39 @@ public function offsetSet($index, $value) {} /** * Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface * - * @param string $offset + * @param mixed $index */ - public function offsetUnset($offset) {} + public function offsetUnset($index) {} /** * Reads an attribute value by its name * - * + * ```php * echo $robot->readAttribute("name"); - * + * ``` * * @param string $attribute - * @return mixed + * @return mixed|null */ - public function readAttribute($attribute) {} + public function readAttribute(string $attribute): ? {} + + /** + * Returns the instance as an array representation + * + * @return array + */ + public function toArray(): array {} /** * Writes an attribute value by its name * - * + * ```php * $robot->writeAttribute("name", "Rosey"); - * + * ``` * * @param string $attribute * @param mixed $value */ - public function writeAttribute($attribute, $value) {} - - /** - * Returns the instance as an array representation - * - * @return array - */ - public function toArray() {} + public function writeAttribute(string $attribute, $value) {} } diff --git a/src/Phalcon/mvc/collection/Manager.php b/src/Phalcon/mvc/collection/Manager.php index dc635c26..8be4af53 100644 --- a/src/Phalcon/mvc/collection/Manager.php +++ b/src/Phalcon/mvc/collection/Manager.php @@ -10,7 +10,7 @@ * * A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\Di. * - * + * ```php * $di = new \Phalcon\Di(); * * $di->set( @@ -21,36 +21,36 @@ * ); * * $robot = new Robots($di); - * + * ``` */ class Manager implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Events\EventsAwareInterface { - protected $_dependencyInjector; + protected $behaviors; - protected $_initialized; + protected $connectionServices; - protected $_lastInitialized; + protected $container; - protected $_eventsManager; + protected $customEventsManager; - protected $_customEventsManager; + protected $eventsManager; - protected $_connectionServices; + protected $implicitObjectsIds; - protected $_implicitObjectsIds; + protected $initialized; - protected $_behaviors; + protected $lastInitialized; - protected $_serviceName = 'mongo'; + protected $serviceName = 'mongo'; @@ -62,138 +62,138 @@ public function getServiceName() {} public function setServiceName($serviceName) {} /** - * Sets the DependencyInjector container + * Binds a behavior to a model * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Mvc\CollectionInterface $model + * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function addBehavior(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Mvc\Collection\BehaviorInterface $behavior) {} /** - * Returns the DependencyInjector container + * Returns a custom events manager related to a model * - * @return \Phalcon\DiInterface + * @param \Phalcon\Mvc\CollectionInterface $model + * @return mixed|null */ - public function getDI() {} + public function getCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model): ? {} /** - * Sets the event manager + * Returns the connection related to a model * - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @param \Phalcon\Mvc\CollectionInterface $model + * @return \Mongo */ - public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + public function getConnection(\Phalcon\Mvc\CollectionInterface $model) {} /** - * Returns the internal event manager + * Gets a connection service for a specific model * - * @return \Phalcon\Events\ManagerInterface + * @param \Phalcon\Mvc\CollectionInterface $model + * @return string */ - public function getEventsManager() {} + public function getConnectionService(\Phalcon\Mvc\CollectionInterface $model): string {} /** - * Sets a custom events manager for a specific model + * Returns the DependencyInjector container * - * @param \Phalcon\Mvc\CollectionInterface $model - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @return \Phalcon\Di\DiInterface */ - public function setCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Events\ManagerInterface $eventsManager) {} + public function getDI(): DiInterface {} /** - * Returns a custom events manager related to a model + * Returns the internal event manager * - * @param \Phalcon\Mvc\CollectionInterface $model - * @return mixed|null + * @return \Phalcon\Events\ManagerInterface */ - public function getCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model) {} + public function getEventsManager(): ManagerInterface {} /** - * Initializes a model in the models manager + * Get the latest initialized model * - * @param \Phalcon\Mvc\CollectionInterface $model + * @return \Phalcon\Mvc\CollectionInterface */ - public function initialize(\Phalcon\Mvc\CollectionInterface $model) {} + public function getLastInitialized(): CollectionInterface {} /** - * Check whether a model is already initialized + * Checks if a model is using implicit object ids * - * @param string $modelName + * @param \Phalcon\Mvc\CollectionInterface $model * @return bool */ - public function isInitialized($modelName) {} + public function isUsingImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model): bool {} /** - * Get the latest initialized model + * Check whether a model is already initialized * - * @return \Phalcon\Mvc\CollectionInterface + * @param string $className + * @return bool */ - public function getLastInitialized() {} + public function isInitialized(string $className): bool {} /** - * Sets a connection service for a specific model + * Initializes a model in the models manager * * @param \Phalcon\Mvc\CollectionInterface $model - * @param string $connectionService */ - public function setConnectionService(\Phalcon\Mvc\CollectionInterface $model, $connectionService) {} + public function initialize(\Phalcon\Mvc\CollectionInterface $model) {} /** - * Gets a connection service for a specific model + * Dispatch an event to the listeners and behaviors + * This method expects that the endpoint listeners/behaviors returns true + * meaning that at least one was implemented * * @param \Phalcon\Mvc\CollectionInterface $model - * @return string + * @param string $eventName + * @param mixed $data + * @return bool */ - public function getConnectionService(\Phalcon\Mvc\CollectionInterface $model) {} + public function missingMethod(\Phalcon\Mvc\CollectionInterface $model, string $eventName, $data): bool {} /** - * Sets whether a model must use implicit objects ids + * Receives events generated in the models and dispatches them to an events-manager if available + * Notify the behaviors that are listening in the model * + * @param string $eventName * @param \Phalcon\Mvc\CollectionInterface $model - * @param bool $useImplicitObjectIds */ - public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, $useImplicitObjectIds) {} + public function notifyEvent(string $eventName, \Phalcon\Mvc\CollectionInterface $model) {} /** - * Checks if a model is using implicit object ids + * Sets a custom events manager for a specific model * * @param \Phalcon\Mvc\CollectionInterface $model - * @return bool + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function isUsingImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model) {} + public function setCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Returns the connection related to a model + * Sets a connection service for a specific model * * @param \Phalcon\Mvc\CollectionInterface $model - * @return \Mongo + * @param string $connectionService */ - public function getConnection(\Phalcon\Mvc\CollectionInterface $model) {} + public function setConnectionService(\Phalcon\Mvc\CollectionInterface $model, string $connectionService) {} /** - * Receives events generated in the models and dispatches them to an events-manager if available - * Notify the behaviors that are listening in the model + * Sets the DependencyInjector container * - * @param string $eventName - * @param \Phalcon\Mvc\CollectionInterface $model + * @param \Phalcon\Di\DiInterface $container */ - public function notifyEvent($eventName, \Phalcon\Mvc\CollectionInterface $model) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Dispatch an event to the listeners and behaviors - * This method expects that the endpoint listeners/behaviors returns true - * meaning that at least one was implemented + * Sets the event manager * - * @param \Phalcon\Mvc\CollectionInterface $model - * @param string $eventName - * @param mixed $data - * @return bool + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function missingMethod(\Phalcon\Mvc\CollectionInterface $model, $eventName, $data) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} /** - * Binds a behavior to a model + * Sets whether a model must use implicit objects ids * * @param \Phalcon\Mvc\CollectionInterface $model - * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior + * @param bool $useImplicitObjectIds */ - public function addBehavior(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Mvc\Collection\BehaviorInterface $behavior) {} + public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, bool $useImplicitObjectIds) {} } diff --git a/src/Phalcon/mvc/collection/ManagerInterface.php b/src/Phalcon/mvc/collection/ManagerInterface.php index da8edc32..1d575f79 100644 --- a/src/Phalcon/mvc/collection/ManagerInterface.php +++ b/src/Phalcon/mvc/collection/ManagerInterface.php @@ -10,7 +10,7 @@ * * A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\Di. * - * + * ```php * $di = new \Phalcon\Di(); * * $di->set( @@ -21,64 +21,56 @@ * ); * * $robot = new Robots(di); - * + * ``` */ interface ManagerInterface { /** - * Sets a custom events manager for a specific model + * Binds a behavior to a collection * * @param \Phalcon\Mvc\CollectionInterface $model - * @param \Phalcon\Events\ManagerInterface $eventsManager + * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior */ - public function setCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Events\ManagerInterface $eventsManager); + public function addBehavior(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Mvc\Collection\BehaviorInterface $behavior); /** - * Returns a custom events manager related to a model + * Returns the connection related to a model * * @param \Phalcon\Mvc\CollectionInterface $model - * @return \Phalcon\Events\ManagerInterface + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function getCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model); + public function getConnection(\Phalcon\Mvc\CollectionInterface $model): AdapterInterface; /** - * Initializes a model in the models manager + * Returns a custom events manager related to a model * * @param \Phalcon\Mvc\CollectionInterface $model + * @return \Phalcon\Events\ManagerInterface */ - public function initialize(\Phalcon\Mvc\CollectionInterface $model); - - /** - * Check whether a model is already initialized - * - * @param string $modelName - * @return bool - */ - public function isInitialized($modelName); + public function getCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model): EventsManagerInterface; /** * Get the latest initialized model * * @return \Phalcon\Mvc\CollectionInterface */ - public function getLastInitialized(); + public function getLastInitialized(): CollectionInterface; /** - * Sets a connection service for a specific model + * Initializes a model in the models manager * * @param \Phalcon\Mvc\CollectionInterface $model - * @param string $connectionService */ - public function setConnectionService(\Phalcon\Mvc\CollectionInterface $model, $connectionService); + public function initialize(\Phalcon\Mvc\CollectionInterface $model); /** - * Sets if a model must use implicit objects ids + * Check whether a model is already initialized * - * @param \Phalcon\Mvc\CollectionInterface $model - * @param bool $useImplicitObjectIds + * @param string $className + * @return bool */ - public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, $useImplicitObjectIds); + public function isInitialized(string $className): bool; /** * Checks if a model is using implicit object ids @@ -86,31 +78,39 @@ public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, $u * @param \Phalcon\Mvc\CollectionInterface $model * @return bool */ - public function isUsingImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model); + public function isUsingImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model): bool; /** - * Returns the connection related to a model + * Receives events generated in the models and dispatches them to an events-manager if available + * Notify the behaviors that are listening in the model * + * @param string $eventName * @param \Phalcon\Mvc\CollectionInterface $model - * @return \Phalcon\Db\AdapterInterface */ - public function getConnection(\Phalcon\Mvc\CollectionInterface $model); + public function notifyEvent(string $eventName, \Phalcon\Mvc\CollectionInterface $model); /** - * Receives events generated in the models and dispatches them to an events-manager if available - * Notify the behaviors that are listening in the model + * Sets a custom events manager for a specific model * - * @param string $eventName * @param \Phalcon\Mvc\CollectionInterface $model + * @param \Phalcon\Events\ManagerInterface $eventsManager */ - public function notifyEvent($eventName, \Phalcon\Mvc\CollectionInterface $model); + public function setCustomEventsManager(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Events\ManagerInterface $eventsManager); /** - * Binds a behavior to a collection + * Sets a connection service for a specific model * * @param \Phalcon\Mvc\CollectionInterface $model - * @param \Phalcon\Mvc\Collection\BehaviorInterface $behavior + * @param string $connectionService */ - public function addBehavior(\Phalcon\Mvc\CollectionInterface $model, \Phalcon\Mvc\Collection\BehaviorInterface $behavior); + public function setConnectionService(\Phalcon\Mvc\CollectionInterface $model, string $connectionService); + + /** + * Sets if a model must use implicit objects ids + * + * @param \Phalcon\Mvc\CollectionInterface $model + * @param bool $useImplicitObjectIds + */ + public function useImplicitObjectIds(\Phalcon\Mvc\CollectionInterface $model, bool $useImplicitObjectIds); } diff --git a/src/Phalcon/mvc/collection/behavior/SoftDelete.php b/src/Phalcon/mvc/collection/behavior/SoftDelete.php index 59621249..18c2959f 100644 --- a/src/Phalcon/mvc/collection/behavior/SoftDelete.php +++ b/src/Phalcon/mvc/collection/behavior/SoftDelete.php @@ -17,6 +17,6 @@ class SoftDelete extends \Phalcon\Mvc\Collection\Behavior * @param string $type * @param \Phalcon\Mvc\CollectionInterface $model */ - public function notify($type, \Phalcon\Mvc\CollectionInterface $model) {} + public function notify(string $type, \Phalcon\Mvc\CollectionInterface $model) {} } diff --git a/src/Phalcon/mvc/collection/behavior/Timestampable.php b/src/Phalcon/mvc/collection/behavior/Timestampable.php index d9803981..09ebb023 100644 --- a/src/Phalcon/mvc/collection/behavior/Timestampable.php +++ b/src/Phalcon/mvc/collection/behavior/Timestampable.php @@ -17,6 +17,6 @@ class Timestampable extends \Phalcon\Mvc\Collection\Behavior * @param string $type * @param \Phalcon\Mvc\CollectionInterface $model */ - public function notify($type, \Phalcon\Mvc\CollectionInterface $model) {} + public function notify(string $type, \Phalcon\Mvc\CollectionInterface $model) {} } diff --git a/src/Phalcon/mvc/controller/BindModelInterface.php b/src/Phalcon/mvc/controller/BindModelInterface.php index 1bffa5d2..84e98de1 100644 --- a/src/Phalcon/mvc/controller/BindModelInterface.php +++ b/src/Phalcon/mvc/controller/BindModelInterface.php @@ -15,6 +15,6 @@ interface BindModelInterface * * @return string */ - public static function getModelName(); + public static function getModelName(): string; } diff --git a/src/Phalcon/mvc/dispatcher/Exception.php b/src/Phalcon/mvc/dispatcher/Exception.php index 685af95f..b7f06862 100644 --- a/src/Phalcon/mvc/dispatcher/Exception.php +++ b/src/Phalcon/mvc/dispatcher/Exception.php @@ -7,7 +7,7 @@ * * Exceptions thrown in Phalcon\Mvc\Dispatcher will use this class */ -class Exception extends \Phalcon\Exception +class Exception extends \Phalcon\Dispatcher\Exception { } diff --git a/src/Phalcon/mvc/micro/Collection.php b/src/Phalcon/mvc/micro/Collection.php index 8b312466..5c1ba381 100644 --- a/src/Phalcon/mvc/micro/Collection.php +++ b/src/Phalcon/mvc/micro/Collection.php @@ -7,7 +7,7 @@ * * Groups Micro-Mvc handlers as controllers * - * + * ```php * $app = new \Phalcon\Mvc\Micro(); * * $collection = new Collection(); @@ -19,175 +19,185 @@ * $collection->get("/posts/edit/{id}", "edit"); * * $app->mount($collection); - * + * ``` */ class Collection implements \Phalcon\Mvc\Micro\CollectionInterface { - protected $_prefix; + protected $handler; - protected $_lazy; + protected $handlers = array(); - protected $_handler; + protected $lazy; - protected $_handlers; + protected $prefix; /** - * Internal function to add a handler to the group + * Maps a route to a handler that only matches if the HTTP method is DELETE. * - * @param string|array $method * @param string $routePattern - * @param mixed $handler + * @param callable|string $handler * @param string $name + * @return CollectionInterface */ - protected function _addMap($method, $routePattern, $handler, $name) {} + public function delete(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Sets a prefix for all routes added to the collection + * Maps a route to a handler that only matches if the HTTP method is GET. * - * @param string $prefix + * @param string $routePattern + * @param callable|string $handler + * @param string $name * @return CollectionInterface */ - public function setPrefix($prefix) {} + public function get(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Returns the collection prefix if any + * Returns the main handler * - * @return string + * @return mixed */ - public function getPrefix() {} + public function getHandler() {} /** * Returns the registered handlers * * @return array */ - public function getHandlers() {} + public function getHandlers(): array {} /** - * Sets the main handler + * Returns the collection prefix if any * - * @param mixed $handler - * @param boolean $lazy - * @return Collection + * @return string */ - public function setHandler($handler, $lazy = false) {} + public function getPrefix(): string {} /** - * Sets if the main handler must be lazy loaded + * Maps a route to a handler that only matches if the HTTP method is HEAD. * - * @param bool $lazy + * @param string $routePattern + * @param callable|string $handler + * @param string $name * @return CollectionInterface */ - public function setLazy($lazy) {} + public function head(string $routePattern, $handler, string $name = null): CollectionInterface {} /** * Returns if the main handler must be lazy loaded * * @return bool */ - public function isLazy() {} + public function isLazy(): bool {} /** - * Returns the main handler + * Maps a route to a handler. * - * @return mixed + * @param string $routePattern + * @param callable|string $handler + * @param string $name + * @return CollectionInterface */ - public function getHandler() {} + public function map(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Maps a route to a handler + * Maps a route to a handler via methods. + * + * ```php + * $collection->mapVia( + * "/test", + * "indexAction", + * ["POST", "GET"], + * "test" + * ); + * ``` * * @param string $routePattern * @param callable $handler + * @param string|array $method * @param string $name - * @return Collection + * @return CollectionInterface */ - public function map($routePattern, $handler, $name = null) {} + public function mapVia(string $routePattern, $handler, $method, string $name = null): CollectionInterface {} /** - * Maps a route to a handler via methods + * Maps a route to a handler that only matches if the HTTP method is + * OPTIONS. * * @param string $routePattern - * @param callable $handler - * @param string|array $method + * @param callable|string $handler * @param string $name - * @return Collection + * @return CollectionInterface */ - public function mapVia($routePattern, $handler, $method, $name = null) {} + public function options(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is GET + * Maps a route to a handler that only matches if the HTTP method is PATCH. * * @param string $routePattern - * @param callable $handler + * @param callable|string $handler * @param string $name - * @return Collection + * @return CollectionInterface */ - public function get($routePattern, $handler, $name = null) {} + public function patch(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is POST + * Maps a route to a handler that only matches if the HTTP method is POST. * * @param string $routePattern - * @param callable $handler + * @param callable|string $handler * @param string $name - * @return Collection + * @return CollectionInterface */ - public function post($routePattern, $handler, $name = null) {} + public function post(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is PUT + * Maps a route to a handler that only matches if the HTTP method is PUT. * * @param string $routePattern - * @param callable $handler + * @param callable|string $handler * @param string $name - * @return Collection + * @return CollectionInterface */ - public function put($routePattern, $handler, $name = null) {} + public function put(string $routePattern, $handler, string $name = null): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is PATCH + * Sets the main handler. * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return Collection + * @param callable|string $handler + * @param bool $lazy + * @return CollectionInterface */ - public function patch($routePattern, $handler, $name = null) {} + public function setHandler($handler, bool $lazy = false): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is HEAD + * Sets if the main handler must be lazy loaded * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return Collection + * @param bool $lazy + * @return CollectionInterface */ - public function head($routePattern, $handler, $name = null) {} + public function setLazy(bool $lazy): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is DELETE + * Sets a prefix for all routes added to the collection * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return Collection + * @param string $prefix + * @return CollectionInterface */ - public function delete($routePattern, $handler, $name = null) {} + public function setPrefix(string $prefix): CollectionInterface {} /** - * Maps a route to a handler that only matches if the HTTP method is OPTIONS + * Internal function to add a handler to the group. * + * @param string|array $method * @param string $routePattern - * @param callable $handler - * @param mixed $name - * @return Collection + * @param callable|string $handler + * @param string $name */ - public function options($routePattern, $handler, $name = null) {} + protected function addMap($method, string $routePattern, $handler, string $name) {} } diff --git a/src/Phalcon/mvc/micro/CollectionInterface.php b/src/Phalcon/mvc/micro/CollectionInterface.php index ad71ea2e..8254ccc9 100644 --- a/src/Phalcon/mvc/micro/CollectionInterface.php +++ b/src/Phalcon/mvc/micro/CollectionInterface.php @@ -11,57 +11,62 @@ interface CollectionInterface { /** - * Sets a prefix for all routes added to the collection + * Maps a route to a handler that only matches if the HTTP method is DELETE * - * @param string $prefix + * @param string $routePattern + * @param callable $handler + * @param string $name * @return CollectionInterface */ - public function setPrefix($prefix); + public function delete(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Returns the collection prefix if any + * Maps a route to a handler that only matches if the HTTP method is GET * - * @return string + * @param string $routePattern + * @param callable $handler + * @param string $name + * @return CollectionInterface + */ + public function get(string $routePattern, $handler, string $name = null): CollectionInterface; + + /** + * Returns the main handler + * + * @return mixed */ - public function getPrefix(); + public function getHandler(); /** * Returns the registered handlers * * @return array */ - public function getHandlers(); + public function getHandlers(): array; /** - * Sets the main handler + * Returns the collection prefix if any * - * @param mixed $handler - * @param boolean $lazy - * @return \Phalcon\Mvc\Micro\Collection + * @return string */ - public function setHandler($handler, $lazy = false); + public function getPrefix(): string; /** - * Sets if the main handler must be lazy loaded + * Maps a route to a handler that only matches if the HTTP method is HEAD * - * @param bool $lazy + * @param string $routePattern + * @param callable $handler + * @param string $name * @return CollectionInterface */ - public function setLazy($lazy); + public function head(string $routePattern, $handler, string $name = null): CollectionInterface; /** * Returns if the main handler must be lazy loaded * * @return bool */ - public function isLazy(); - - /** - * Returns the main handler - * - * @return mixed - */ - public function getHandler(); + public function isLazy(): bool; /** * Maps a route to a handler @@ -69,78 +74,73 @@ public function getHandler(); * @param string $routePattern * @param callable $handler * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @return CollectionInterface */ - public function map($routePattern, $handler, $name = null); + public function map(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is GET + * Maps a route to a handler that only matches if the HTTP method is OPTIONS * * @param string $routePattern * @param callable $handler * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @return CollectionInterface */ - public function get($routePattern, $handler, $name = null); + public function options(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is POST + * Maps a route to a handler that only matches if the HTTP method is PATCH * * @param string $routePattern * @param callable $handler * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @return CollectionInterface */ - public function post($routePattern, $handler, $name = null); + public function patch(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is PUT + * Maps a route to a handler that only matches if the HTTP method is POST * * @param string $routePattern * @param callable $handler * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @return CollectionInterface */ - public function put($routePattern, $handler, $name = null); + public function post(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is PATCH + * Maps a route to a handler that only matches if the HTTP method is PUT * * @param string $routePattern * @param callable $handler * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @return CollectionInterface */ - public function patch($routePattern, $handler, $name = null); + public function put(string $routePattern, $handler, string $name = null): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is HEAD + * Sets the main handler * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @param mixed $handler + * @param bool $lazy + * @return CollectionInterface */ - public function head($routePattern, $handler, $name = null); + public function setHandler($handler, bool $lazy = false): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is DELETE + * Sets if the main handler must be lazy loaded * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @param bool $lazy + * @return CollectionInterface */ - public function delete($routePattern, $handler, $name = null); + public function setLazy(bool $lazy): CollectionInterface; /** - * Maps a route to a handler that only matches if the HTTP method is OPTIONS + * Sets a prefix for all routes added to the collection * - * @param string $routePattern - * @param callable $handler - * @param string $name - * @return \Phalcon\Mvc\Router\RouteInterface + * @param string $prefix + * @return CollectionInterface */ - public function options($routePattern, $handler, $name = null); + public function setPrefix(string $prefix): CollectionInterface; } diff --git a/src/Phalcon/mvc/micro/Exception.php b/src/Phalcon/mvc/micro/Exception.php index 1c22e5f4..cd352fc1 100644 --- a/src/Phalcon/mvc/micro/Exception.php +++ b/src/Phalcon/mvc/micro/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Mvc\Micro; /** - * Phalcon\Mvc\Micro\Exception - * * Exceptions thrown in Phalcon\Mvc\Micro will use this class */ class Exception extends \Phalcon\Exception diff --git a/src/Phalcon/mvc/micro/LazyLoader.php b/src/Phalcon/mvc/micro/LazyLoader.php index e083b411..d7cb0a66 100644 --- a/src/Phalcon/mvc/micro/LazyLoader.php +++ b/src/Phalcon/mvc/micro/LazyLoader.php @@ -10,13 +10,10 @@ class LazyLoader { - protected $_handler; + protected $handler; - protected $_modelBinder; - - - protected $_definition; + protected $definition; @@ -27,16 +24,7 @@ public function getDefinition() {} * * @param string $definition */ - public function __construct($definition) {} - - /** - * Initializes the internal handler, calling functions on it - * - * @param string $method - * @param array $arguments - * @return mixed - */ - public function __call($method, $arguments) {} + public function __construct(string $definition) {} /** * Calling __call method @@ -46,6 +34,6 @@ public function __call($method, $arguments) {} * @param \Phalcon\Mvc\Model\BinderInterface $modelBinder * @return mixed */ - public function callMethod($method, $arguments, \Phalcon\Mvc\Model\BinderInterface $modelBinder = null) {} + public function callMethod(string $method, $arguments, \Phalcon\Mvc\Model\BinderInterface $modelBinder = null) {} } diff --git a/src/Phalcon/mvc/micro/MiddlewareInterface.php b/src/Phalcon/mvc/micro/MiddlewareInterface.php index ee19ff86..daa73549 100644 --- a/src/Phalcon/mvc/micro/MiddlewareInterface.php +++ b/src/Phalcon/mvc/micro/MiddlewareInterface.php @@ -3,8 +3,6 @@ namespace Phalcon\Mvc\Micro; /** - * Phalcon\Mvc\Micro\MiddlewareInterface - * * Allows to implement Phalcon\Mvc\Micro middleware in classes */ interface MiddlewareInterface diff --git a/src/Phalcon/mvc/model/Behavior.php b/src/Phalcon/mvc/model/Behavior.php index 4c5bc910..e3366fdd 100644 --- a/src/Phalcon/mvc/model/Behavior.php +++ b/src/Phalcon/mvc/model/Behavior.php @@ -9,8 +9,10 @@ */ abstract class Behavior implements \Phalcon\Mvc\Model\BehaviorInterface { - - protected $_options; + /** + * @var array + */ + protected $options; /** @@ -18,39 +20,39 @@ abstract class Behavior implements \Phalcon\Mvc\Model\BehaviorInterface * * @param array $options */ - public function __construct($options = null) {} + public function __construct(array $options = array()) {} /** - * Checks whether the behavior must take action on certain event + * Returns the behavior options related to an event * * @param string $eventName - * @return bool + * @return array */ - protected function mustTakeAction($eventName) {} + protected function getOptions(string $eventName = null) {} /** - * Returns the behavior options related to an event + * Acts as fallbacks when a missing method is called on the model * - * @param string $eventName - * @return array + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $method + * @param array $arguments */ - protected function getOptions($eventName = null) {} + public function missingMethod(\Phalcon\Mvc\ModelInterface $model, string $method, array $arguments = array()) {} /** - * This method receives the notifications from the EventsManager + * Checks whether the behavior must take action on certain event * - * @param string $type - * @param \Phalcon\Mvc\ModelInterface $model + * @param string $eventName + * @return bool */ - public function notify($type, \Phalcon\Mvc\ModelInterface $model) {} + protected function mustTakeAction(string $eventName): bool {} /** - * Acts as fallbacks when a missing method is called on the model + * This method receives the notifications from the EventsManager * + * @param string $type * @param \Phalcon\Mvc\ModelInterface $model - * @param string $method - * @param array $arguments */ - public function missingMethod(\Phalcon\Mvc\ModelInterface $model, $method, $arguments = null) {} + public function notify(string $type, \Phalcon\Mvc\ModelInterface $model) {} } diff --git a/src/Phalcon/mvc/model/BehaviorInterface.php b/src/Phalcon/mvc/model/BehaviorInterface.php index 084b49fd..77ed3cc6 100644 --- a/src/Phalcon/mvc/model/BehaviorInterface.php +++ b/src/Phalcon/mvc/model/BehaviorInterface.php @@ -11,20 +11,20 @@ interface BehaviorInterface { /** - * This method receives the notifications from the EventsManager + * Calls a method when it's missing in the model * - * @param string $type * @param \Phalcon\Mvc\ModelInterface $model + * @param string $method + * @param array $arguments */ - public function notify($type, \Phalcon\Mvc\ModelInterface $model); + public function missingMethod(\Phalcon\Mvc\ModelInterface $model, string $method, array $arguments = array()); /** - * Calls a method when it's missing in the model + * This method receives the notifications from the EventsManager * + * @param string $type * @param \Phalcon\Mvc\ModelInterface $model - * @param string $method - * @param array $arguments */ - public function missingMethod(\Phalcon\Mvc\ModelInterface $model, $method, $arguments = null); + public function notify(string $type, \Phalcon\Mvc\ModelInterface $model); } diff --git a/src/Phalcon/mvc/model/Binder.php b/src/Phalcon/mvc/model/Binder.php index dbe0bf78..086ca316 100644 --- a/src/Phalcon/mvc/model/Binder.php +++ b/src/Phalcon/mvc/model/Binder.php @@ -37,7 +37,7 @@ class Binder implements \Phalcon\Mvc\Model\BinderInterface * * @return array */ - public function getBoundModels() {} + public function getBoundModels(): array {} /** * Array for original values @@ -47,24 +47,9 @@ public function getOriginalValues() {} /** * Phalcon\Mvc\Model\Binder constructor * - * @param \Phalcon\Cache\BackendInterface $cache + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache */ - public function __construct(\Phalcon\Cache\BackendInterface $cache = null) {} - - /** - * Gets cache instance - * - * @param \Phalcon\Cache\BackendInterface $cache - * @return BinderInterface - */ - public function setCache(\Phalcon\Cache\BackendInterface $cache) {} - - /** - * Sets cache instance - * - * @return \Phalcon\Cache\BackendInterface - */ - public function getCache() {} + public function __construct(\Phalcon\Cache\Adapter\AdapterInterface $cache = null) {} /** * Bind models into params in proper handler @@ -72,10 +57,10 @@ public function getCache() {} * @param object $handler * @param array $params * @param string $cacheKey - * @param mixed $methodName + * @param string $methodName * @return array */ - public function bindToHandler($handler, array $params, $cacheKey, $methodName = null) {} + public function bindToHandler($handler, array $params, string $cacheKey, string $methodName = null): array {} /** * Find the model by param value. @@ -84,7 +69,14 @@ public function bindToHandler($handler, array $params, $cacheKey, $methodName = * @param string $className * @return object|bool */ - protected function findBoundModel($paramValue, $className) {} + protected function findBoundModel($paramValue, string $className): bool {} + + /** + * Sets cache instance + * + * @return \Phalcon\Cache\Adapter\AdapterInterface + */ + public function getCache(): AdapterInterface {} /** * Get params classes from cache by key @@ -92,7 +84,7 @@ protected function findBoundModel($paramValue, $className) {} * @param string $cacheKey * @return array|null */ - protected function getParamsFromCache($cacheKey) {} + protected function getParamsFromCache(string $cacheKey): ?array {} /** * Get modified params for handler using reflection @@ -100,9 +92,17 @@ protected function getParamsFromCache($cacheKey) {} * @param object $handler * @param array $params * @param string $cacheKey - * @param mixed $methodName + * @param string $methodName * @return array */ - protected function getParamsFromReflection($handler, array $params, $cacheKey, $methodName) {} + protected function getParamsFromReflection($handler, array $params, string $cacheKey, string $methodName): array {} + + /** + * Gets cache instance + * + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache + * @return BinderInterface + */ + public function setCache(\Phalcon\Cache\Adapter\AdapterInterface $cache): BinderInterface {} } diff --git a/src/Phalcon/mvc/model/BinderInterface.php b/src/Phalcon/mvc/model/BinderInterface.php index ddd77ec2..811f792e 100644 --- a/src/Phalcon/mvc/model/BinderInterface.php +++ b/src/Phalcon/mvc/model/BinderInterface.php @@ -11,36 +11,36 @@ interface BinderInterface { /** - * Gets active bound models + * Bind models into params in proper handler * + * @param object $handler + * @param array $params + * @param string $cacheKey + * @param string $methodName * @return array */ - public function getBoundModels(); + public function bindToHandler($handler, array $params, string $cacheKey, string $methodName = null): array; /** - * Gets cache instance + * Gets active bound models * - * @return \Phalcon\Cache\BackendInterface + * @return array */ - public function getCache(); + public function getBoundModels(): array; /** - * Sets cache instance + * Gets cache instance * - * @param \Phalcon\Cache\BackendInterface $cache - * @return BinderInterface + * @return \Phalcon\Cache\Adapter\AdapterInterface */ - public function setCache(\Phalcon\Cache\BackendInterface $cache); + public function getCache(): AdapterInterface; /** - * Bind models into params in proper handler + * Sets cache instance * - * @param object $handler - * @param array $params - * @param string $cacheKey - * @param mixed $methodName - * @return array + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache + * @return BinderInterface */ - public function bindToHandler($handler, array $params, $cacheKey, $methodName = null); + public function setCache(\Phalcon\Cache\Adapter\AdapterInterface $cache): BinderInterface; } diff --git a/src/Phalcon/mvc/model/Criteria.php b/src/Phalcon/mvc/model/Criteria.php index e39987a0..99b5a18f 100644 --- a/src/Phalcon/mvc/model/Criteria.php +++ b/src/Phalcon/mvc/model/Criteria.php @@ -6,10 +6,10 @@ * Phalcon\Mvc\Model\Criteria * * This class is used to build the array parameter required by - * Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() - * using an object-oriented interface. + * Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() using an + * object-oriented interface. * - * + * ```php * $robots = Robots::query() * ->where("type = :type:") * ->andWhere("year < 2000") @@ -17,39 +17,39 @@ * ->limit(5, 10) * ->orderBy("name") * ->execute(); - * + * ``` */ class Criteria implements \Phalcon\Mvc\Model\CriteriaInterface, \Phalcon\Di\InjectionAwareInterface { - protected $_model; + protected $bindParams; - protected $_params; + protected $bindTypes; - protected $_bindParams; + protected $hiddenParamNumber = 0; - protected $_bindTypes; + protected $model; - protected $_hiddenParamNumber = 0; + protected $params = array(); /** * Sets the DependencyInjector container * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** * Returns the DependencyInjector container * - * @return null|\Phalcon\DiInterface + * @return \Phalcon\Di\DiInterface */ - public function getDI() {} + public function getDI(): DiInterface {} /** * Set a model on which the query will be executed @@ -57,14 +57,14 @@ public function getDI() {} * @param string $modelName * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function setModelName($modelName) {} + public function setModelName(string $modelName): CriteriaInterface {} /** * Returns an internal model name on which the criteria will be applied * * @return string */ - public function getModelName() {} + public function getModelName(): string {} /** * Sets the bound parameters in the criteria @@ -74,7 +74,7 @@ public function getModelName() {} * @param bool $merge * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function bind(array $bindParams, $merge = false) {} + public function bind(array $bindParams, bool $merge = false): CriteriaInterface {} /** * Sets the bind types in the criteria @@ -83,94 +83,130 @@ public function bind(array $bindParams, $merge = false) {} * @param array $bindTypes * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function bindTypes(array $bindTypes) {} + public function bindTypes(array $bindTypes): CriteriaInterface {} /** * Sets SELECT DISTINCT / SELECT ALL flag * * @param mixed $distinct - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function distinct($distinct) {} + public function distinct($distinct): CriteriaInterface {} /** * Sets the columns to be queried * - * + * ```php * $criteria->columns( * [ * "id", * "name", * ] * ); - * + * ``` * * @param string|array $columns - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function columns($columns) {} + public function columns($columns): CriteriaInterface {} /** * Adds an INNER join to the query * - * - * $criteria->join("Robots"); - * $criteria->join("Robots", "r.id = RobotsParts.robots_id"); - * $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); - * $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); - * + * ```php + * $criteria->join( + * Robots::class + * ); + * + * $criteria->join( + * Robots::class, + * "r.id = RobotsParts.robots_id" + * ); + * + * $criteria->join( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * + * $criteria->join( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r", + * "LEFT" + * ); + * ``` * * @param string $model * @param mixed $conditions * @param mixed $alias * @param mixed $type - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function join($model, $conditions = null, $alias = null, $type = null) {} + public function join(string $model, $conditions = null, $alias = null, $type = null): CriteriaInterface {} /** * Adds an INNER join to the query * - * - * $criteria->innerJoin("Robots"); - * $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); - * $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * ```php + * $criteria->innerJoin( + * Robots::class + * ); + * + * $criteria->innerJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id" + * ); + * + * $criteria->innerJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` * * @param string $model * @param mixed $conditions * @param mixed $alias - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function innerJoin($model, $conditions = null, $alias = null) {} + public function innerJoin(string $model, $conditions = null, $alias = null): CriteriaInterface {} /** * Adds a LEFT join to the query * - * - * $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * ```php + * $criteria->leftJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` * * @param string $model * @param mixed $conditions * @param mixed $alias - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function leftJoin($model, $conditions = null, $alias = null) {} + public function leftJoin(string $model, $conditions = null, $alias = null): CriteriaInterface {} /** * Adds a RIGHT join to the query * - * - * $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * ```php + * $criteria->rightJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` * * @param string $model * @param mixed $conditions * @param mixed $alias - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function rightJoin($model, $conditions = null, $alias = null) {} + public function rightJoin(string $model, $conditions = null, $alias = null): CriteriaInterface {} /** * Sets the conditions parameter in the criteria @@ -180,20 +216,7 @@ public function rightJoin($model, $conditions = null, $alias = null) {} * @param mixed $bindTypes * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function where($conditions, $bindParams = null, $bindTypes = null) {} - - /** - * Appends a condition to the current conditions using an AND operator (deprecated) - * - * @deprecated 1.0.0 - * @see \Phalcon\Mvc\Model\Criteria::andWhere() - * @param string $conditions - * @param mixed $bindParams - * @param mixed $bindTypes - * @deprecated - * @return Criteria - */ - public function addWhere($conditions, $bindParams = null, $bindTypes = null) {} + public function where(string $conditions, $bindParams = null, $bindTypes = null): CriteriaInterface {} /** * Appends a condition to the current conditions using an AND operator @@ -203,7 +226,7 @@ public function addWhere($conditions, $bindParams = null, $bindTypes = null) {} * @param mixed $bindTypes * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function andWhere($conditions, $bindParams = null, $bindTypes = null) {} + public function andWhere(string $conditions, $bindParams = null, $bindTypes = null): CriteriaInterface {} /** * Appends a condition to the current conditions using an OR operator @@ -213,61 +236,61 @@ public function andWhere($conditions, $bindParams = null, $bindTypes = null) {} * @param mixed $bindTypes * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function orWhere($conditions, $bindParams = null, $bindTypes = null) {} + public function orWhere(string $conditions, $bindParams = null, $bindTypes = null): CriteriaInterface {} /** * Appends a BETWEEN condition to the current conditions * - * + * ```php * $criteria->betweenWhere("price", 100.25, 200.50); - * + * ``` * * @param string $expr * @param mixed $minimum * @param mixed $maximum * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function betweenWhere($expr, $minimum, $maximum) {} + public function betweenWhere(string $expr, $minimum, $maximum): CriteriaInterface {} /** * Appends a NOT BETWEEN condition to the current conditions * - * + * ```php * $criteria->notBetweenWhere("price", 100.25, 200.50); - * + * ``` * * @param string $expr * @param mixed $minimum * @param mixed $maximum * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function notBetweenWhere($expr, $minimum, $maximum) {} + public function notBetweenWhere(string $expr, $minimum, $maximum): CriteriaInterface {} /** * Appends an IN condition to the current conditions * - * + * ```php * $criteria->inWhere("id", [1, 2, 3]); - * + * ``` * * @param string $expr * @param array $values * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function inWhere($expr, array $values) {} + public function inWhere(string $expr, array $values): CriteriaInterface {} /** * Appends a NOT IN condition to the current conditions * - * + * ```php * $criteria->notInWhere("id", [1, 2, 3]); - * + * ``` * * @param string $expr * @param array $values * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function notInWhere($expr, array $values) {} + public function notInWhere(string $expr, array $values): CriteriaInterface {} /** * Adds the conditions parameter to the criteria @@ -275,17 +298,7 @@ public function notInWhere($expr, array $values) {} * @param string $conditions * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function conditions($conditions) {} - - /** - * Adds the order-by parameter to the criteria (deprecated) - * - * @see \Phalcon\Mvc\Model\Criteria::orderBy() - * @param string $orderColumns - * @deprecated - * @return Criteria - */ - public function order($orderColumns) {} + public function conditions(string $conditions): CriteriaInterface {} /** * Adds the order-by clause to the criteria @@ -293,38 +306,38 @@ public function order($orderColumns) {} * @param string $orderColumns * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function orderBy($orderColumns) {} + public function orderBy(string $orderColumns): CriteriaInterface {} /** * Adds the group-by clause to the criteria * * @param mixed $group - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function groupBy($group) {} + public function groupBy($group): CriteriaInterface {} /** * Adds the having clause to the criteria * * @param mixed $having - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function having($having) {} + public function having($having): CriteriaInterface {} /** * Adds the limit parameter to the criteria. * - * + * ```php * $criteria->limit(100); * $criteria->limit(100, 200); * $criteria->limit("100", "200"); - * + * ``` * * @param int $limit - * @param mixed $offset + * @param int $offset * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function limit($limit, $offset = null) {} + public function limit(int $limit, int $offset = 0): CriteriaInterface {} /** * Adds the "for_update" parameter to the criteria @@ -332,7 +345,7 @@ public function limit($limit, $offset = null) {} * @param bool $forUpdate * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function forUpdate($forUpdate = true) {} + public function forUpdate(bool $forUpdate = true): CriteriaInterface {} /** * Adds the "shared_lock" parameter to the criteria @@ -340,54 +353,53 @@ public function forUpdate($forUpdate = true) {} * @param bool $sharedLock * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function sharedLock($sharedLock = true) {} + public function sharedLock(bool $sharedLock = true): CriteriaInterface {} /** * Sets the cache options in the criteria * This method replaces all previously set cache options * * @param array $cache - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public function cache(array $cache) {} + public function cache(array $cache): CriteriaInterface {} /** * Returns the conditions parameter in the criteria * * @return string|null */ - public function getWhere() {} + public function getWhere(): ?string {} /** * Returns the columns to be queried * * @return string|null */ - public function getColumns() {} + public function getColumns(): ?string {} /** * Returns the conditions parameter in the criteria * * @return string|null */ - public function getConditions() {} + public function getConditions(): ?string {} /** - * Returns the limit parameter in the criteria, which will be - * an integer if limit was set without an offset, - * an array with 'number' and 'offset' keys if an offset was set with the limit, - * or null if limit has not been set. + * Returns the limit parameter in the criteria, which will be an integer if + * limit was set without an offset, an array with 'number' and 'offset' keys + * if an offset was set with the limit, or null if limit has not been set. * * @return string|null */ - public function getLimit() {} + public function getLimit(): ?string {} /** * Returns the order clause in the criteria * * @return string|null */ - public function getOrderBy() {} + public function getOrderBy(): ?string {} /** * Returns the group clause in the criteria @@ -404,38 +416,38 @@ public function getHaving() {} * * @return array */ - public function getParams() {} + public function getParams(): array {} /** * Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @param string $modelName * @param array $data * @param string $operator - * @return Criteria + * @return \Phalcon\Mvc\Model\CriteriaInterface */ - public static function fromInput(\Phalcon\DiInterface $dependencyInjector, $modelName, array $data, $operator = 'AND') {} + public static function fromInput(\Phalcon\Di\DiInterface $container, string $modelName, array $data, string $operator = 'AND'): CriteriaInterface {} /** * Creates a query builder from criteria. * - * + * ```php * $builder = Robots::query() * ->where("type = :type:") * ->bind(["type" => "mechanical"]) * ->createBuilder(); - * + * ``` * * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function createBuilder() {} + public function createBuilder(): BuilderInterface {} /** * Executes a find using the parameters built with the criteria * * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public function execute() {} + public function execute(): ResultsetInterface {} } diff --git a/src/Phalcon/mvc/model/CriteriaInterface.php b/src/Phalcon/mvc/model/CriteriaInterface.php index cd77f6dc..923f16b8 100644 --- a/src/Phalcon/mvc/model/CriteriaInterface.php +++ b/src/Phalcon/mvc/model/CriteriaInterface.php @@ -11,29 +11,37 @@ interface CriteriaInterface { /** - * Set a model on which the query will be executed + * Appends a condition to the current conditions using an AND operator * - * @param string $modelName + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes * @return CriteriaInterface */ - public function setModelName($modelName); + public function andWhere(string $conditions, $bindParams = null, $bindTypes = null): CriteriaInterface; /** - * Returns an internal model name on which the criteria will be applied + * Appends a BETWEEN condition to the current conditions * - * @return string + * ```php + * $criteria->betweenWhere("price", 100.25, 200.50); + * ``` + * + * @param string $expr + * @param mixed $minimum + * @param mixed $maximum + * @return CriteriaInterface */ - public function getModelName(); + public function betweenWhere(string $expr, $minimum, $maximum): CriteriaInterface; /** * Sets the bound parameters in the criteria * This method replaces all previously set bound parameters * * @param array $bindParams - * @param bool $merge * @return CriteriaInterface */ - public function bind(array $bindParams, $merge = false); + public function bind(array $bindParams): CriteriaInterface; /** * Sets the bind types in the criteria @@ -42,17 +50,16 @@ public function bind(array $bindParams, $merge = false); * @param array $bindTypes * @return CriteriaInterface */ - public function bindTypes(array $bindTypes); + public function bindTypes(array $bindTypes): CriteriaInterface; /** - * Sets the conditions parameter in the criteria + * Sets the cache options in the criteria + * This method replaces all previously set cache options * - * @param string $conditions - * @param mixed $bindParams - * @param mixed $bindTypes + * @param array $cache * @return CriteriaInterface */ - public function where($conditions, $bindParams = null, $bindTypes = null); + public function cache(array $cache): CriteriaInterface; /** * Adds the conditions parameter to the criteria @@ -60,24 +67,22 @@ public function where($conditions, $bindParams = null, $bindTypes = null); * @param string $conditions * @return CriteriaInterface */ - public function conditions($conditions); + public function conditions(string $conditions): CriteriaInterface; /** - * Adds the order-by parameter to the criteria + * Sets SELECT DISTINCT / SELECT ALL flag * - * @param string $orderColumns + * @param mixed $distinct * @return CriteriaInterface */ - public function orderBy($orderColumns); + public function distinct($distinct): CriteriaInterface; /** - * Sets the limit parameter to the criteria + * Executes a find using the parameters built with the criteria * - * @param int $limit - * @param int $offset - * @return CriteriaInterface + * @return ResultsetInterface */ - public function limit($limit, $offset = null); + public function execute(): ResultsetInterface; /** * Sets the "for_update" parameter to the criteria @@ -85,133 +90,237 @@ public function limit($limit, $offset = null); * @param bool $forUpdate * @return CriteriaInterface */ - public function forUpdate($forUpdate = true); + public function forUpdate(bool $forUpdate = true): CriteriaInterface; /** - * Sets the "shared_lock" parameter to the criteria + * Returns the columns to be queried * - * @param bool $sharedLock + * @return string|null + */ + public function getColumns(): ?string; + + /** + * Returns the conditions parameter in the criteria + * + * @return string|null + */ + public function getConditions(): ?string; + + /** + * Returns the group clause in the criteria + */ + public function getGroupBy(); + + /** + * Returns the having clause in the criteria + */ + public function getHaving(); + + /** + * Returns the limit parameter in the criteria, which will be an integer if + * limit was set without an offset, an array with 'number' and 'offset' keys + * if an offset was set with the limit, or null if limit has not been set. + * + * @return string|null + */ + public function getLimit(): ?string; + + /** + * Returns an internal model name on which the criteria will be applied + * + * @return string + */ + public function getModelName(): string; + + /** + * Returns the order parameter in the criteria + * + * @return string|null + */ + public function getOrderBy(): ?string; + + /** + * Returns all the parameters defined in the criteria + * + * @return array + */ + public function getParams(): array; + + /** + * Returns the conditions parameter in the criteria + * + * @return string|null + */ + public function getWhere(): ?string; + + /** + * Adds the group-by clause to the criteria + * + * @param mixed $group * @return CriteriaInterface */ - public function sharedLock($sharedLock = true); + public function groupBy($group): CriteriaInterface; /** - * Appends a condition to the current conditions using an AND operator + * Adds the having clause to the criteria * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes + * @param mixed $having * @return CriteriaInterface */ - public function andWhere($conditions, $bindParams = null, $bindTypes = null); + public function having($having): CriteriaInterface; /** - * Appends a condition to the current conditions using an OR operator + * Adds an INNER join to the query * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes + * ```php + * $criteria->innerJoin( + * Robots::class + * ); + * + * $criteria->innerJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id" + * ); + * + * $criteria->innerJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` + * + * @param string $model + * @param mixed $conditions + * @param mixed $alias * @return CriteriaInterface */ - public function orWhere($conditions, $bindParams = null, $bindTypes = null); + public function innerJoin(string $model, $conditions = null, $alias = null): CriteriaInterface; /** - * Appends a BETWEEN condition to the current conditions + * Appends an IN condition to the current conditions * - * - * $criteria->betweenWhere("price", 100.25, 200.50); - * + * ```php + * $criteria->inWhere("id", [1, 2, 3]); + * ``` * * @param string $expr - * @param mixed $minimum - * @param mixed $maximum + * @param array $values * @return CriteriaInterface */ - public function betweenWhere($expr, $minimum, $maximum); + public function inWhere(string $expr, array $values): CriteriaInterface; /** - * Appends a NOT BETWEEN condition to the current conditions + * Adds a LEFT join to the query * - * - * $criteria->notBetweenWhere("price", 100.25, 200.50); - * + * ```php + * $criteria->leftJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` * - * @param string $expr - * @param mixed $minimum - * @param mixed $maximum + * @param string $model + * @param mixed $conditions + * @param mixed $alias * @return CriteriaInterface */ - public function notBetweenWhere($expr, $minimum, $maximum); + public function leftJoin(string $model, $conditions = null, $alias = null): CriteriaInterface; /** - * Appends an IN condition to the current conditions + * Sets the limit parameter to the criteria * - * - * $criteria->inWhere("id", [1, 2, 3]); - * + * @param int $limit + * @param int $offset + * @return CriteriaInterface + */ + public function limit(int $limit, int $offset = 0): CriteriaInterface; + + /** + * Appends a NOT BETWEEN condition to the current conditions + * + * ```php + * $criteria->notBetweenWhere("price", 100.25, 200.50); + * ``` * * @param string $expr - * @param array $values + * @param mixed $minimum + * @param mixed $maximum * @return CriteriaInterface */ - public function inWhere($expr, array $values); + public function notBetweenWhere(string $expr, $minimum, $maximum): CriteriaInterface; /** * Appends a NOT IN condition to the current conditions * - * + * ```php * $criteria->notInWhere("id", [1, 2, 3]); - * + * ``` * * @param string $expr * @param array $values * @return CriteriaInterface */ - public function notInWhere($expr, array $values); + public function notInWhere(string $expr, array $values): CriteriaInterface; /** - * Returns the conditions parameter in the criteria + * Adds the order-by parameter to the criteria * - * @return string|null + * @param string $orderColumns + * @return CriteriaInterface */ - public function getWhere(); + public function orderBy(string $orderColumns): CriteriaInterface; /** - * Returns the conditions parameter in the criteria + * Appends a condition to the current conditions using an OR operator * - * @return string|null + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return CriteriaInterface */ - public function getConditions(); + public function orWhere(string $conditions, $bindParams = null, $bindTypes = null): CriteriaInterface; /** - * Returns the limit parameter in the criteria, which will be - * an integer if limit was set without an offset, - * an array with 'number' and 'offset' keys if an offset was set with the limit, - * or null if limit has not been set. + * Adds a RIGHT join to the query * - * @return int|array|null + * ```php + * $criteria->rightJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` + * + * @param string $model + * @param mixed $conditions + * @param mixed $alias + * @return CriteriaInterface */ - public function getLimit(); + public function rightJoin(string $model, $conditions = null, $alias = null): CriteriaInterface; /** - * Returns the order parameter in the criteria + * Set a model on which the query will be executed * - * @return string|null + * @param string $modelName + * @return CriteriaInterface */ - public function getOrderBy(); + public function setModelName(string $modelName): CriteriaInterface; /** - * Returns all the parameters defined in the criteria + * Sets the "shared_lock" parameter to the criteria * - * @return array + * @param bool $sharedLock + * @return CriteriaInterface */ - public function getParams(); + public function sharedLock(bool $sharedLock = true): CriteriaInterface; /** - * Executes a find using the parameters built with the criteria + * Sets the conditions parameter in the criteria * - * @return ResultsetInterface + * @param string $conditions + * @return CriteriaInterface */ - public function execute(); + public function where(string $conditions): CriteriaInterface; } diff --git a/src/Phalcon/mvc/model/Manager.php b/src/Phalcon/mvc/model/Manager.php index f83fe1c8..a398bec4 100644 --- a/src/Phalcon/mvc/model/Manager.php +++ b/src/Phalcon/mvc/model/Manager.php @@ -5,12 +5,13 @@ /** * Phalcon\Mvc\Model\Manager * - * This components controls the initialization of models, keeping record of relations - * between the different models of the application. + * This components controls the initialization of models, keeping record of + * relations between the different models of the application. * - * A ModelsManager is injected to a model via a Dependency Injector/Services Container such as Phalcon\Di. + * A ModelsManager is injected to a model via a Dependency Injector/Services + * Container such as Phalcon\Di. * - * + * ```php * use Phalcon\Di; * use Phalcon\Mvc\Model\Manager as ModelsManager; * @@ -24,145 +25,142 @@ * ); * * $robot = new Robots($di); - * + * ``` */ class Manager implements \Phalcon\Mvc\Model\ManagerInterface, \Phalcon\Di\InjectionAwareInterface, \Phalcon\Events\EventsAwareInterface { - protected $_dependencyInjector; - - - protected $_eventsManager; + protected $aliases = array(); + /** + * Models' behaviors + */ + protected $behaviors = array(); - protected $_customEventsManager; + /** + * Belongs to relations + */ + protected $belongsTo = array(); + /** + * All the relationships by model + */ + protected $belongsToSingle = array(); - protected $_readConnectionServices; + protected $container; - protected $_writeConnectionServices; + protected $customEventsManager = array(); - protected $_aliases; + /** + * Does the model use dynamic update, instead of updating all rows? + */ + protected $dynamicUpdate = array(); - protected $_modelVisibility = array(); + protected $eventsManager; /** * Has many relations */ - protected $_hasMany; + protected $hasMany = array(); /** * Has many relations by model */ - protected $_hasManySingle; + protected $hasManySingle = array(); /** - * Has one relations + * Has many-Through relations */ - protected $_hasOne; + protected $hasManyToMany = array(); /** - * Has one relations by model + * Has many-Through relations by model */ - protected $_hasOneSingle; + protected $hasManyToManySingle = array(); /** - * Belongs to relations + * Has one relations */ - protected $_belongsTo; + protected $hasOne = array(); /** - * All the relationships by model + * Has one relations by model */ - protected $_belongsToSingle; + protected $hasOneSingle = array(); /** - * Has many-Through relations + * Mark initialized models */ - protected $_hasManyToMany; + protected $initialized = array(); + + + protected $keepSnapshots = array(); /** - * Has many-Through relations by model + * Last model initialized */ - protected $_hasManyToManySingle; + protected $lastInitialized; /** - * Mark initialized models + * Last query created/executed */ - protected $_initialized; + protected $lastQuery; - protected $_prefix = ''; + protected $modelVisibility = array(); - protected $_sources; + protected $prefix = ''; - protected $_schemas; + protected $readConnectionServices = array(); - /** - * Models' behaviors - */ - protected $_behaviors; - /** - * Last model initialized - */ - protected $_lastInitialized; + protected $sources = array(); - /** - * Last query created/executed - */ - protected $_lastQuery; - /** - * Stores a list of reusable instances - */ - protected $_reusable; + protected $schemas = array(); - protected $_keepSnapshots; + protected $writeConnectionServices = array(); /** - * Does the model use dynamic update, instead of updating all rows? + * Stores a list of reusable instances */ - protected $_dynamicUpdate; - - - protected $_namespaceAliases; + protected $reusable = array(); /** * Sets the DependencyInjector container * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** * Returns the DependencyInjector container * - * @return \Phalcon\DiInterface + * @return \Phalcon\Di\DiInterface */ - public function getDI() {} + public function getDI(): DiInterface {} /** * Sets a global events manager * * @param \Phalcon\Events\ManagerInterface $eventsManager - * @return Manager + * @return \Phalcon\Mvc\Model\ManagerInterface */ - public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager) {} + public function setEventsManager(\Phalcon\Events\ManagerInterface $eventsManager): ManagerInterface {} /** * Returns the internal event manager * * @return \Phalcon\Events\ManagerInterface */ - public function getEventsManager() {} + public function getEventsManager(): EventsManagerInterface {} /** * Sets a custom events manager for a specific model @@ -186,73 +184,63 @@ public function getCustomEventsManager(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @return bool */ - public function initialize(\Phalcon\Mvc\ModelInterface $model) {} + public function initialize(\Phalcon\Mvc\ModelInterface $model): bool {} /** * Check whether a model is already initialized * - * @param string $modelName + * @param string $className * @return bool */ - public function isInitialized($modelName) {} + public function isInitialized(string $className): bool {} /** * Get last initialized model * * @return \Phalcon\Mvc\ModelInterface */ - public function getLastInitialized() {} + public function getLastInitialized(): ModelInterface {} /** * Loads a model throwing an exception if it doesn't exist * * @param string $modelName - * @param bool $newInstance * @return \Phalcon\Mvc\ModelInterface */ - public function load($modelName, $newInstance = false) {} + public function load(string $modelName): ModelInterface {} /** * Sets the prefix for all model sources. * - * + * ```php * use Phalcon\Mvc\Model\Manager; * - * $di->set("modelsManager", function () { - * $modelsManager = new Manager(); - * $modelsManager->setModelPrefix("wp_"); + * $di->set( + * "modelsManager", + * function () { + * $modelsManager = new Manager(); * - * return $modelsManager; - * }); + * $modelsManager->setModelPrefix("wp_"); + * + * return $modelsManager; + * } + * ); * * $robots = new Robots(); + * * echo $robots->getSource(); // wp_robots - * + * ``` * * @param string $prefix */ - public function setModelPrefix($prefix) {} + public function setModelPrefix(string $prefix) {} /** * Returns the prefix for all model sources. * - * - * use Phalcon\Mvc\Model\Manager; - * - * $di->set("modelsManager", function () { - * $modelsManager = new Manager(); - * $modelsManager->setModelPrefix("wp_"); - * - * return $modelsManager; - * }); - * - * $robots = new Robots(); - * echo $robots->getSource(); // wp_robots - * - * * @return string */ - public function getModelPrefix() {} + public function getModelPrefix(): string {} /** * Sets the mapped source for a model @@ -260,23 +248,23 @@ public function getModelPrefix() {} * @param \Phalcon\Mvc\ModelInterface $model * @param string $source */ - public function setModelSource(\Phalcon\Mvc\ModelInterface $model, $source) {} + public function setModelSource(\Phalcon\Mvc\ModelInterface $model, string $source) {} /** * Check whether a model property is declared as public. * - * + * ```php * $isPublic = $manager->isVisibleModelProperty( * new Robots(), * "name" * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @param string $property * @return bool */ - public final function isVisibleModelProperty(\Phalcon\Mvc\ModelInterface $model, $property) {} + final public function isVisibleModelProperty(\Phalcon\Mvc\ModelInterface $model, string $property): bool {} /** * Returns the mapped source for a model @@ -284,7 +272,7 @@ public final function isVisibleModelProperty(\Phalcon\Mvc\ModelInterface $model, * @param \Phalcon\Mvc\ModelInterface $model * @return string */ - public function getModelSource(\Phalcon\Mvc\ModelInterface $model) {} + public function getModelSource(\Phalcon\Mvc\ModelInterface $model): string {} /** * Sets the mapped schema for a model @@ -292,7 +280,7 @@ public function getModelSource(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @param string $schema */ - public function setModelSchema(\Phalcon\Mvc\ModelInterface $model, $schema) {} + public function setModelSchema(\Phalcon\Mvc\ModelInterface $model, string $schema) {} /** * Returns the mapped schema for a model @@ -300,7 +288,7 @@ public function setModelSchema(\Phalcon\Mvc\ModelInterface $model, $schema) {} * @param \Phalcon\Mvc\ModelInterface $model * @return string */ - public function getModelSchema(\Phalcon\Mvc\ModelInterface $model) {} + public function getModelSchema(\Phalcon\Mvc\ModelInterface $model): string {} /** * Sets both write and read connection service for a model @@ -308,7 +296,7 @@ public function getModelSchema(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @param string $connectionService */ - public function setConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService) {} + public function setConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService) {} /** * Sets write connection service for a model @@ -316,7 +304,7 @@ public function setConnectionService(\Phalcon\Mvc\ModelInterface $model, $connec * @param \Phalcon\Mvc\ModelInterface $model * @param string $connectionService */ - public function setWriteConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService) {} + public function setWriteConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService) {} /** * Sets read connection service for a model @@ -324,32 +312,32 @@ public function setWriteConnectionService(\Phalcon\Mvc\ModelInterface $model, $c * @param \Phalcon\Mvc\ModelInterface $model * @param string $connectionService */ - public function setReadConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService) {} + public function setReadConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService) {} /** * Returns the connection to read data related to a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return \Phalcon\Db\AdapterInterface + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function getReadConnection(\Phalcon\Mvc\ModelInterface $model) {} + public function getReadConnection(\Phalcon\Mvc\ModelInterface $model): AdapterInterface {} /** * Returns the connection to write data related to a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return \Phalcon\Db\AdapterInterface + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function getWriteConnection(\Phalcon\Mvc\ModelInterface $model) {} + public function getWriteConnection(\Phalcon\Mvc\ModelInterface $model): AdapterInterface {} /** * Returns the connection to read or write data related to a model depending on the connection services. * * @param \Phalcon\Mvc\ModelInterface $model * @param mixed $connectionServices - * @return \Phalcon\Db\AdapterInterface + * @return \Phalcon\Db\Adapter\AdapterInterface */ - protected function _getConnection(\Phalcon\Mvc\ModelInterface $model, $connectionServices) {} + protected function _getConnection(\Phalcon\Mvc\ModelInterface $model, $connectionServices): AdapterInterface {} /** * Returns the connection service name used to read data related to a model @@ -357,7 +345,7 @@ protected function _getConnection(\Phalcon\Mvc\ModelInterface $model, $connectio * @param \Phalcon\Mvc\ModelInterface $model * @return string */ - public function getReadConnectionService(\Phalcon\Mvc\ModelInterface $model) {} + public function getReadConnectionService(\Phalcon\Mvc\ModelInterface $model): string {} /** * Returns the connection service name used to write data related to a model @@ -365,7 +353,7 @@ public function getReadConnectionService(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @return string */ - public function getWriteConnectionService(\Phalcon\Mvc\ModelInterface $model) {} + public function getWriteConnectionService(\Phalcon\Mvc\ModelInterface $model): string {} /** * Returns the connection service name used to read or write data related to @@ -375,16 +363,17 @@ public function getWriteConnectionService(\Phalcon\Mvc\ModelInterface $model) {} * @param mixed $connectionServices * @return string */ - public function _getConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionServices) {} + public function _getConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionServices): string {} /** - * Receives events generated in the models and dispatches them to an events-manager if available - * Notify the behaviors that are listening in the model + * Receives events generated in the models and dispatches them to an + * events-manager if available. Notify the behaviors that are listening in + * the model * * @param string $eventName * @param \Phalcon\Mvc\ModelInterface $model */ - public function notifyEvent($eventName, \Phalcon\Mvc\ModelInterface $model) {} + public function notifyEvent(string $eventName, \Phalcon\Mvc\ModelInterface $model) {} /** * Dispatch an event to the listeners and behaviors @@ -395,7 +384,7 @@ public function notifyEvent($eventName, \Phalcon\Mvc\ModelInterface $model) {} * @param string $eventName * @param mixed $data */ - public function missingMethod(\Phalcon\Mvc\ModelInterface $model, $eventName, $data) {} + public function missingMethod(\Phalcon\Mvc\ModelInterface $model, string $eventName, $data) {} /** * Binds a behavior to a model @@ -411,7 +400,7 @@ public function addBehavior(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Mvc\Mod * @param \Phalcon\Mvc\ModelInterface $model * @param bool $keepSnapshots */ - public function keepSnapshots(\Phalcon\Mvc\ModelInterface $model, $keepSnapshots) {} + public function keepSnapshots(\Phalcon\Mvc\ModelInterface $model, bool $keepSnapshots) {} /** * Checks if a model is keeping snapshots for the queried records @@ -419,7 +408,7 @@ public function keepSnapshots(\Phalcon\Mvc\ModelInterface $model, $keepSnapshots * @param \Phalcon\Mvc\ModelInterface $model * @return bool */ - public function isKeepingSnapshots(\Phalcon\Mvc\ModelInterface $model) {} + public function isKeepingSnapshots(\Phalcon\Mvc\ModelInterface $model): bool {} /** * Sets if a model must use dynamic update instead of the all-field update @@ -427,7 +416,7 @@ public function isKeepingSnapshots(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @param bool $dynamicUpdate */ - public function useDynamicUpdate(\Phalcon\Mvc\ModelInterface $model, $dynamicUpdate) {} + public function useDynamicUpdate(\Phalcon\Mvc\ModelInterface $model, bool $dynamicUpdate) {} /** * Checks if a model is using dynamic update instead of all-field update @@ -435,78 +424,58 @@ public function useDynamicUpdate(\Phalcon\Mvc\ModelInterface $model, $dynamicUpd * @param \Phalcon\Mvc\ModelInterface $model * @return bool */ - public function isUsingDynamicUpdate(\Phalcon\Mvc\ModelInterface $model) {} + public function isUsingDynamicUpdate(\Phalcon\Mvc\ModelInterface $model): bool {} /** * Setup a 1-1 relation between two models * - * @param mixed fields - * @param string referencedModel - * @param mixed referencedFields - * @param array options - * @param \Phalcon\Mvc\Model $model + * @param \Phalcon\Mvc\ModelInterface $model * @param mixed $fields * @param string $referencedModel * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\Relation + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function addHasOne(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null) {} + public function addHasOne(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface {} /** * Setup a relation reverse many to one between two models * - * @param mixed fields - * @param string referencedModel - * @param mixed referencedFields - * @param array options - * @param \Phalcon\Mvc\Model $model + * @param \Phalcon\Mvc\ModelInterface $model * @param mixed $fields * @param string $referencedModel * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\Relation + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function addBelongsTo(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null) {} + public function addBelongsTo(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface {} /** * Setup a relation 1-n between two models * - * @param mixed fields - * @param string referencedModel - * @param mixed referencedFields - * @param array options * @param \Phalcon\Mvc\ModelInterface $model * @param mixed $fields * @param string $referencedModel * @param mixed $referencedFields - * @param mixed $options - * @param $Phalcon\Mvc\ModelInterface model - * @return \Phalcon\Mvc\Model\Relation + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function addHasMany(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null) {} + public function addHasMany(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface {} /** * Setups a relation n-m between two models * - * @param string fields - * @param string intermediateModel - * @param string intermediateFields - * @param string intermediateReferencedFields - * @param string referencedModel - * @param string referencedFields * @param \Phalcon\Mvc\ModelInterface $model - * @param mixed $fields + * @param string $fields * @param string $intermediateModel - * @param mixed $intermediateFields - * @param mixed $intermediateReferencedFields + * @param string $intermediateFields + * @param string $intermediateReferencedFields * @param string $referencedModel - * @param mixed $referencedFields + * @param string $referencedFields * @param array $options - * @param $Phalcon\Mvc\ModelInterface model - * @return \Phalcon\Mvc\Model\Relation + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function addHasManyToMany(\Phalcon\Mvc\ModelInterface $model, $fields, $intermediateModel, $intermediateFields, $intermediateReferencedFields, $referencedModel, $referencedFields, $options = null) {} + public function addHasManyToMany(\Phalcon\Mvc\ModelInterface $model, $fields, string $intermediateModel, $intermediateFields, $intermediateReferencedFields, string $referencedModel, $referencedFields, $options = null): RelationInterface {} /** * Checks whether a model has a belongsTo relation with another model @@ -515,7 +484,7 @@ public function addHasManyToMany(\Phalcon\Mvc\ModelInterface $model, $fields, $i * @param string $modelRelation * @return bool */ - public function existsBelongsTo($modelName, $modelRelation) {} + public function existsBelongsTo(string $modelName, string $modelRelation): bool {} /** * Checks whether a model has a hasMany relation with another model @@ -524,7 +493,7 @@ public function existsBelongsTo($modelName, $modelRelation) {} * @param string $modelRelation * @return bool */ - public function existsHasMany($modelName, $modelRelation) {} + public function existsHasMany(string $modelName, string $modelRelation): bool {} /** * Checks whether a model has a hasOne relation with another model @@ -533,7 +502,7 @@ public function existsHasMany($modelName, $modelRelation) {} * @param string $modelRelation * @return bool */ - public function existsHasOne($modelName, $modelRelation) {} + public function existsHasOne(string $modelName, string $modelRelation): bool {} /** * Checks whether a model has a hasManyToMany relation with another model @@ -542,16 +511,16 @@ public function existsHasOne($modelName, $modelRelation) {} * @param string $modelRelation * @return bool */ - public function existsHasManyToMany($modelName, $modelRelation) {} + public function existsHasManyToMany(string $modelName, string $modelRelation): bool {} /** * Returns a relation by its alias * * @param string $modelName * @param string $alias - * @return bool|\Phalcon\Mvc\Model\Relation + * @return bool|\Phalcon\Mvc\Model\RelationInterface */ - public function getRelationByAlias($modelName, $alias) {} + public function getRelationByAlias(string $modelName, string $alias) {} /** * Merge two arrays of find parameters @@ -560,18 +529,18 @@ public function getRelationByAlias($modelName, $alias) {} * @param mixed $findParamsTwo * @return array */ - protected final function _mergeFindParameters($findParamsOne, $findParamsTwo) {} + final protected function _mergeFindParameters($findParamsOne, $findParamsTwo): array {} /** * Helper method to query records based on a relation definition * * @param \Phalcon\Mvc\Model\RelationInterface $relation - * @param string $method * @param \Phalcon\Mvc\ModelInterface $record * @param mixed $parameters + * @param string $method * @return \Phalcon\Mvc\Model\Resultset\Simple|Phalcon\Mvc\Model\Resultset\Simple|int|false */ - public function getRelationRecords(\Phalcon\Mvc\Model\RelationInterface $relation, $method, \Phalcon\Mvc\ModelInterface $record, $parameters = null) {} + public function getRelationRecords(\Phalcon\Mvc\Model\RelationInterface $relation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null) {} /** * Returns a reusable object from the internal list @@ -579,7 +548,7 @@ public function getRelationRecords(\Phalcon\Mvc\Model\RelationInterface $relatio * @param string $modelName * @param string $key */ - public function getReusableRecords($modelName, $key) {} + public function getReusableRecords(string $modelName, string $key) {} /** * Stores a reusable record in the internal list @@ -588,7 +557,7 @@ public function getReusableRecords($modelName, $key) {} * @param string $key * @param mixed $records */ - public function setReusableRecords($modelName, $key, $records) {} + public function setReusableRecords(string $modelName, string $key, $records) {} /** * Clears the internal reusable list @@ -598,52 +567,52 @@ public function clearReusableObjects() {} /** * Gets belongsTo related records from a model * - * @param string $method * @param string $modelName - * @param mixed $modelRelation + * @param string $modelRelation * @param \Phalcon\Mvc\ModelInterface $record * @param mixed $parameters + * @param string $method * @return bool|\Phalcon\Mvc\Model\ResultsetInterface */ - public function getBelongsToRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null) {} + public function getBelongsToRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null) {} /** * Gets hasMany related records from a model * - * @param string $method * @param string $modelName - * @param mixed $modelRelation + * @param string $modelRelation * @param \Phalcon\Mvc\ModelInterface $record * @param mixed $parameters + * @param string $method * @return bool|\Phalcon\Mvc\Model\ResultsetInterface */ - public function getHasManyRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null) {} + public function getHasManyRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null) {} /** * Gets belongsTo related records from a model * - * @param string $method * @param string $modelName - * @param mixed $modelRelation + * @param string $modelRelation * @param \Phalcon\Mvc\ModelInterface $record * @param mixed $parameters + * @param string $method * @return bool|\Phalcon\Mvc\ModelInterface */ - public function getHasOneRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null) {} + public function getHasOneRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null) {} /** * Gets all the belongsTo relations defined in a model * - * + * ```php * $relations = $modelsManager->getBelongsTo( * new Robots() * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getBelongsTo(\Phalcon\Mvc\ModelInterface $model) {} + public function getBelongsTo(\Phalcon\Mvc\ModelInterface $model): array {} /** * Gets hasMany relations defined on a model @@ -651,7 +620,7 @@ public function getBelongsTo(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getHasMany(\Phalcon\Mvc\ModelInterface $model) {} + public function getHasMany(\Phalcon\Mvc\ModelInterface $model): array {} /** * Gets hasOne relations defined on a model @@ -659,7 +628,7 @@ public function getHasMany(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getHasOne(\Phalcon\Mvc\ModelInterface $model) {} + public function getHasOne(\Phalcon\Mvc\ModelInterface $model): array {} /** * Gets hasManyToMany relations defined on a model @@ -667,32 +636,32 @@ public function getHasOne(\Phalcon\Mvc\ModelInterface $model) {} * @param \Phalcon\Mvc\ModelInterface $model * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getHasManyToMany(\Phalcon\Mvc\ModelInterface $model) {} + public function getHasManyToMany(\Phalcon\Mvc\ModelInterface $model): array {} /** * Gets hasOne relations defined on a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return \Phalcon\Mvc\Model\RelationInterface[] + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getHasOneAndHasMany(\Phalcon\Mvc\ModelInterface $model) {} + public function getHasOneAndHasMany(\Phalcon\Mvc\ModelInterface $model): array {} /** * Query all the relationships defined on a model * * @param string $modelName - * @return \Phalcon\Mvc\Model\RelationInterface[] + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getRelations($modelName) {} + public function getRelations(string $modelName): array {} /** * Query the first relationship defined between two models * * @param string $first * @param string $second - * @return bool|\Phalcon\Mvc\Model\RelationInterface[] + * @return array|bool|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getRelationsBetween($first, $second) {} + public function getRelationsBetween(string $first, string $second) {} /** * Creates a Phalcon\Mvc\Model\Query without execute it @@ -700,7 +669,7 @@ public function getRelationsBetween($first, $second) {} * @param string $phql * @return \Phalcon\Mvc\Model\QueryInterface */ - public function createQuery($phql) {} + public function createQuery(string $phql): QueryInterface {} /** * Creates a Phalcon\Mvc\Model\Query and execute it @@ -710,7 +679,7 @@ public function createQuery($phql) {} * @param mixed $types * @return \Phalcon\Mvc\Model\QueryInterface */ - public function executeQuery($phql, $placeholders = null, $types = null) {} + public function executeQuery(string $phql, $placeholders = null, $types = null): QueryInterface {} /** * Creates a Phalcon\Mvc\Model\Query\Builder @@ -718,37 +687,14 @@ public function executeQuery($phql, $placeholders = null, $types = null) {} * @param mixed $params * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function createBuilder($params = null) {} + public function createBuilder($params = null): BuilderInterface {} /** * Returns the last query created or executed in the models manager * * @return \Phalcon\Mvc\Model\QueryInterface */ - public function getLastQuery() {} - - /** - * Registers shorter aliases for namespaces in PHQL statements - * - * @param string $alias - * @param string $namespaceName - */ - public function registerNamespaceAlias($alias, $namespaceName) {} - - /** - * Returns a real namespace from its alias - * - * @param string $alias - * @return string - */ - public function getNamespaceAlias($alias) {} - - /** - * Returns all the registered namespace aliases - * - * @return array - */ - public function getNamespaceAliases() {} + public function getLastQuery(): QueryInterface {} /** * Destroys the current PHQL cache diff --git a/src/Phalcon/mvc/model/ManagerInterface.php b/src/Phalcon/mvc/model/ManagerInterface.php index 27bc4070..9cd12efc 100644 --- a/src/Phalcon/mvc/model/ManagerInterface.php +++ b/src/Phalcon/mvc/model/ManagerInterface.php @@ -11,331 +11,362 @@ interface ManagerInterface { /** - * Initializes a model in the model manager + * Binds a behavior to a model * * @param \Phalcon\Mvc\ModelInterface $model + * @param \Phalcon\Mvc\Model\BehaviorInterface $behavior */ - public function initialize(\Phalcon\Mvc\ModelInterface $model); + public function addBehavior(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Mvc\Model\BehaviorInterface $behavior); /** - * Sets the mapped source for a model + * Setup a relation reverse 1-1 between two models * * @param \Phalcon\Mvc\ModelInterface $model - * @param string $source + * @param mixed $fields + * @param string $referencedModel + * @param mixed $referencedFields + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function setModelSource(\Phalcon\Mvc\ModelInterface $model, $source); + public function addBelongsTo(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface; /** - * Returns the mapped source for a model + * Setup a relation 1-n between two models * * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @param mixed $fields + * @param string $referencedModel + * @param mixed $referencedFields + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function getModelSource(\Phalcon\Mvc\ModelInterface $model); + public function addHasMany(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface; /** - * Sets the mapped schema for a model + * Setup a 1-1 relation between two models * * @param \Phalcon\Mvc\ModelInterface $model - * @param string $schema + * @param mixed $fields + * @param string $referencedModel + * @param mixed $referencedFields + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function setModelSchema(\Phalcon\Mvc\ModelInterface $model, $schema); + public function addHasOne(\Phalcon\Mvc\ModelInterface $model, $fields, string $referencedModel, $referencedFields, $options = null): RelationInterface; /** - * Returns the mapped schema for a model + * Setups a relation n-m between two models * * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @param string $fields + * @param string $intermediateModel + * @param string $intermediateFields + * @param string $intermediateReferencedFields + * @param string $referencedModel + * @param string $referencedFields + * @param array $options + * @return \Phalcon\Mvc\Model\RelationInterface */ - public function getModelSchema(\Phalcon\Mvc\ModelInterface $model); + public function addHasManyToMany(\Phalcon\Mvc\ModelInterface $model, $fields, string $intermediateModel, $intermediateFields, $intermediateReferencedFields, string $referencedModel, $referencedFields, $options = null): RelationInterface; /** - * Sets both write and read connection service for a model + * Creates a Phalcon\Mvc\Model\Query\Builder * - * @param \Phalcon\Mvc\ModelInterface $model - * @param string $connectionService + * @param string $params + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function setConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService); + public function createBuilder($params = null): BuilderInterface; /** - * Sets read connection service for a model + * Creates a Phalcon\Mvc\Model\Query without execute it * - * @param \Phalcon\Mvc\ModelInterface $model - * @param string $connectionService + * @param string $phql + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setReadConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService); + public function createQuery(string $phql): QueryInterface; /** - * Returns the connection service name used to read data related to a model + * Creates a Phalcon\Mvc\Model\Query and execute it * - * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @param string $phql + * @param array $placeholders + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function getReadConnectionService(\Phalcon\Mvc\ModelInterface $model); + public function executeQuery(string $phql, $placeholders = null): QueryInterface; /** - * Sets write connection service for a model + * Checks whether a model has a belongsTo relation with another model * - * @param \Phalcon\Mvc\ModelInterface $model - * @param string $connectionService + * @param string $modelName + * @param string $modelRelation + * @return bool */ - public function setWriteConnectionService(\Phalcon\Mvc\ModelInterface $model, $connectionService); + public function existsBelongsTo(string $modelName, string $modelRelation): bool; /** - * Returns the connection service name used to write data related to a model + * Checks whether a model has a hasMany relation with another model * - * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @param string $modelName + * @param string $modelRelation + * @return bool */ - public function getWriteConnectionService(\Phalcon\Mvc\ModelInterface $model); + public function existsHasMany(string $modelName, string $modelRelation): bool; /** - * Returns the connection to read data related to a model + * Checks whether a model has a hasOne relation with another model * - * @param \Phalcon\Mvc\ModelInterface $model - * @return \Phalcon\Db\AdapterInterface + * @param string $modelName + * @param string $modelRelation + * @return bool */ - public function getReadConnection(\Phalcon\Mvc\ModelInterface $model); + public function existsHasOne(string $modelName, string $modelRelation): bool; /** - * Returns the connection to write data related to a model + * Checks whether a model has a hasManyToMany relation with another model + * + * @param string $modelName + * @param string $modelRelation + * @return bool + */ + public function existsHasManyToMany(string $modelName, string $modelRelation): bool; + + /** + * Gets belongsTo relations defined on a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return \Phalcon\Db\AdapterInterface + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getWriteConnection(\Phalcon\Mvc\ModelInterface $model); + public function getBelongsTo(\Phalcon\Mvc\ModelInterface $model): array; /** - * Check of a model is already initialized + * Gets belongsTo related records from a model * * @param string $modelName - * @return bool + * @param string $modelRelation + * @param ModelInterface $record + * @param array|string|null $parameters + * @param string|null $method + * @return bool|ResultsetInterface */ - public function isInitialized($modelName); + public function getBelongsToRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null); /** - * Get last initialized model + * Gets hasMany relations defined on a model * - * @return \Phalcon\Mvc\ModelInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getLastInitialized(); + public function getHasMany(\Phalcon\Mvc\ModelInterface $model): array; /** - * Loads a model throwing an exception if it doesn't exist + * Gets hasMany related records from a model * * @param string $modelName - * @param bool $newInstance - * @return \Phalcon\Mvc\ModelInterface + * @param string $modelRelation + * @param ModelInterface $record + * @param array|string|null $parameters + * @param string|null $method + * @return bool|ResultsetInterface */ - public function load($modelName, $newInstance = false); + public function getHasManyRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null); /** - * Setup a 1-1 relation between two models + * Gets hasManyToMany relations defined on a model * - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param array $options * @param \Phalcon\Mvc\ModelInterface $model - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param mixed $options - * @return \Phalcon\Mvc\Model\RelationInterface + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function addHasOne(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null); + public function getHasManyToMany(\Phalcon\Mvc\ModelInterface $model): array; /** - * Setup a relation reverse 1-1 between two models + * Gets hasOne relations defined on a model * - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param array $options * @param \Phalcon\Mvc\ModelInterface $model - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param mixed $options - * @param $\Phalcon\Mvc\ModelInterface $model - * @return + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function addBelongsTo(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null); + public function getHasOne(\Phalcon\Mvc\ModelInterface $model): array; /** - * Setup a relation 1-n between two models + * Gets hasOne relations defined on a model * - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param array $options * @param \Phalcon\Mvc\ModelInterface $model - * @param mixed $fields - * @param string $referencedModel - * @param mixed $referencedFields - * @param mixed $options - * @param $\Phalcon\Mvc\ModelInterface $model - * @return + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function addHasMany(\Phalcon\Mvc\ModelInterface $model, $fields, $referencedModel, $referencedFields, $options = null); + public function getHasOneAndHasMany(\Phalcon\Mvc\ModelInterface $model): array; /** - * Checks whether a model has a belongsTo relation with another model + * Gets belongsTo related records from a model * * @param string $modelName * @param string $modelRelation - * @param $string $modelRelation - * @return + * @param ModelInterface $record + * @param array|string|null $parameters + * @param string|null $method + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function existsBelongsTo($modelName, $modelRelation); + public function getHasOneRecords(string $modelName, string $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null); /** - * Checks whether a model has a hasMany relation with another model + * Get last initialized model * - * @param string $modelName - * @param string $modelRelation - * @param $string $modelRelation - * @return + * @return \Phalcon\Mvc\ModelInterface */ - public function existsHasMany($modelName, $modelRelation); + public function getLastInitialized(): ModelInterface; /** - * Checks whether a model has a hasOne relation with another model + * Returns the last query created or executed in the models manager * - * @param string $modelName - * @param string $modelRelation - * @param $string $modelRelation - * @return + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function existsHasOne($modelName, $modelRelation); + public function getLastQuery(): QueryInterface; /** - * Gets belongsTo related records from a model + * Returns the mapped schema for a model * - * @param string $method - * @param string $modelName - * @param string $modelRelation - * @param \Phalcon\Mvc\Model $record - * @param array $parameters - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return string */ - public function getBelongsToRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null); + public function getModelSchema(\Phalcon\Mvc\ModelInterface $model): string; /** - * Gets hasMany related records from a model + * Returns the mapped source for a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @return string + */ + public function getModelSource(\Phalcon\Mvc\ModelInterface $model): string; + + /** + * Returns the connection to read data related to a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @return \Phalcon\Db\Adapter\AdapterInterface + */ + public function getReadConnection(\Phalcon\Mvc\ModelInterface $model): AdapterInterface; + + /** + * Returns the connection service name used to read data related to a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @return string + */ + public function getReadConnectionService(\Phalcon\Mvc\ModelInterface $model): string; + + /** + * Returns a relation by its alias * - * @param string $method * @param string $modelName - * @param string $modelRelation - * @param \Phalcon\Mvc\Model $record - * @param array $parameters - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @param string $alias + * @return bool|Relation */ - public function getHasManyRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null); + public function getRelationByAlias(string $modelName, string $alias); /** - * Gets belongsTo related records from a model + * Helper method to query records based on a relation definition * + * @param \Phalcon\Mvc\Model\RelationInterface $relation + * @param \Phalcon\Mvc\ModelInterface $record + * @param mixed $parameters * @param string $method - * @param string $modelName - * @param string $modelRelation - * @param \Phalcon\Mvc\Model $record - * @param array $parameters - * @return \Phalcon\Mvc\Model\ResultsetInterface + * @return \Phalcon\Mvc\Model\Resultset\Simple|Phalcon\Mvc\Model\Resultset\Simple|int|false */ - public function getHasOneRecords($method, $modelName, $modelRelation, \Phalcon\Mvc\ModelInterface $record, $parameters = null); + public function getRelationRecords(\Phalcon\Mvc\Model\RelationInterface $relation, \Phalcon\Mvc\ModelInterface $record, $parameters = null, string $method = null); /** - * Gets belongsTo relations defined on a model + * Query all the relationships defined on a model * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param string $modelName + * @return array|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getBelongsTo(\Phalcon\Mvc\ModelInterface $model); + public function getRelations(string $modelName): array; /** - * Gets hasMany relations defined on a model + * Query the relations between two models * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param string $first + * @param string $second + * @return array|bool|\Phalcon\Mvc\Model\RelationInterface[] */ - public function getHasMany(\Phalcon\Mvc\ModelInterface $model); + public function getRelationsBetween(string $first, string $second); /** - * Gets hasOne relations defined on a model + * Returns the connection to write data related to a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function getHasOne(\Phalcon\Mvc\ModelInterface $model); + public function getWriteConnection(\Phalcon\Mvc\ModelInterface $model): AdapterInterface; /** - * Gets hasOne relations defined on a model + * Returns the connection service name used to write data related to a model * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return string */ - public function getHasOneAndHasMany(\Phalcon\Mvc\ModelInterface $model); + public function getWriteConnectionService(\Phalcon\Mvc\ModelInterface $model): string; /** - * Query all the relationships defined on a model + * Loads a model throwing an exception if it doesn't exist * * @param string $modelName - * @return \Phalcon\Mvc\Model\RelationInterface[] + * @return \Phalcon\Mvc\ModelInterface */ - public function getRelations($modelName); + public function load(string $modelName): ModelInterface; /** - * Query the relations between two models + * Initializes a model in the model manager * - * @param string $first - * @param string $second - * @return array + * @param \Phalcon\Mvc\ModelInterface $model */ - public function getRelationsBetween($first, $second); + public function initialize(\Phalcon\Mvc\ModelInterface $model); /** - * Creates a Phalcon\Mvc\Model\Query without execute it + * Check of a model is already initialized * - * @param string $phql - * @return \Phalcon\Mvc\Model\QueryInterface + * @param string $className + * @return bool */ - public function createQuery($phql); + public function isInitialized(string $className): bool; /** - * Creates a Phalcon\Mvc\Model\Query and execute it + * Checks if a model is keeping snapshots for the queried records * - * @param string $phql - * @param array $placeholders - * @param array $types - * @return \Phalcon\Mvc\Model\QueryInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return bool */ - public function executeQuery($phql, $placeholders = null, $types = null); + public function isKeepingSnapshots(\Phalcon\Mvc\ModelInterface $model): bool; /** - * Creates a Phalcon\Mvc\Model\Query\Builder + * Checks if a model is using dynamic update instead of all-field update * - * @param string $params - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return bool */ - public function createBuilder($params = null); + public function isUsingDynamicUpdate(\Phalcon\Mvc\ModelInterface $model): bool; /** - * Binds a behavior to a model + * Check whether a model property is declared as public. + * + * ```php + * $isPublic = $manager->isVisibleModelProperty( + * new Robots(), + * "name" + * ); + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\Mvc\Model\BehaviorInterface $behavior + * @param string $property + * @return bool */ - public function addBehavior(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Mvc\Model\BehaviorInterface $behavior); + final public function isVisibleModelProperty(\Phalcon\Mvc\ModelInterface $model, string $property): bool; /** - * Receives events generated in the models and dispatches them to an events-manager if available - * Notify the behaviors that are listening in the model + * Sets if a model must keep snapshots * - * @param string $eventName * @param \Phalcon\Mvc\ModelInterface $model + * @param bool $keepSnapshots */ - public function notifyEvent($eventName, \Phalcon\Mvc\ModelInterface $model); + public function keepSnapshots(\Phalcon\Mvc\ModelInterface $model, bool $keepSnapshots); /** * Dispatch an event to the listeners and behaviors @@ -345,24 +376,65 @@ public function notifyEvent($eventName, \Phalcon\Mvc\ModelInterface $model); * @param \Phalcon\Mvc\ModelInterface $model * @param string $eventName * @param array $data - * @return boolean + * @return bool */ - public function missingMethod(\Phalcon\Mvc\ModelInterface $model, $eventName, $data); + public function missingMethod(\Phalcon\Mvc\ModelInterface $model, string $eventName, $data); /** - * Returns the last query created or executed in the models manager + * Receives events generated in the models and dispatches them to an events-manager if available + * Notify the behaviors that are listening in the model * - * @return \Phalcon\Mvc\Model\QueryInterface + * @param string $eventName + * @param \Phalcon\Mvc\ModelInterface $model */ - public function getLastQuery(); + public function notifyEvent(string $eventName, \Phalcon\Mvc\ModelInterface $model); /** - * Returns a relation by its alias + * Sets both write and read connection service for a model * - * @param string $modelName - * @param string $alias - * @return \Phalcon\Mvc\Model\Relation + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $connectionService + */ + public function setConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService); + + /** + * Sets read connection service for a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $connectionService + */ + public function setReadConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService); + + /** + * Sets the mapped schema for a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $schema + */ + public function setModelSchema(\Phalcon\Mvc\ModelInterface $model, string $schema); + + /** + * Sets the mapped source for a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $source + */ + public function setModelSource(\Phalcon\Mvc\ModelInterface $model, string $source); + + /** + * Sets write connection service for a model + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $connectionService + */ + public function setWriteConnectionService(\Phalcon\Mvc\ModelInterface $model, string $connectionService); + + /** + * Sets if a model must use dynamic update instead of the all-field update + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param bool $dynamicUpdate */ - public function getRelationByAlias($modelName, $alias); + public function useDynamicUpdate(\Phalcon\Mvc\ModelInterface $model, bool $dynamicUpdate); } diff --git a/src/Phalcon/mvc/model/Message.php b/src/Phalcon/mvc/model/Message.php deleted file mode 100644 index 971efcd9..00000000 --- a/src/Phalcon/mvc/model/Message.php +++ /dev/null @@ -1,147 +0,0 @@ - - * use Phalcon\Mvc\Model\Message as Message; - * - * class Robots extends \Phalcon\Mvc\Model - * { - * public function beforeSave() - * { - * if ($this->name === "Peter") { - * $text = "A robot cannot be named Peter"; - * $field = "name"; - * $type = "InvalidValue"; - * - * $message = new Message($text, $field, $type); - * - * $this->appendMessage($message); - * } - * } - * } - * - */ -class Message implements \Phalcon\Mvc\Model\MessageInterface -{ - /** - * @var string - */ - protected $_type; - - /** - * @var string - */ - protected $_message; - - - protected $_field; - - - protected $_model; - - - protected $_code; - - - /** - * @return string - */ - public function getType() {} - - /** - * @return string - */ - public function getMessage() {} - - /** - * Phalcon\Mvc\Model\Message constructor - * - * @param string $message - * @param string|array $field - * @param string $type - * @param \Phalcon\Mvc\ModelInterface $model - * @param int|null $code - */ - public function __construct($message, $field = null, $type = null, $model = null, $code = null) {} - - /** - * Sets message type - * - * @param string $type - * @return Message - */ - public function setType($type) {} - - /** - * Sets verbose message - * - * @param string $message - * @return Message - */ - public function setMessage($message) {} - - /** - * Sets field name related to message - * - * @param mixed $field - * @return Message - */ - public function setField($field) {} - - /** - * Returns field name related to message - */ - public function getField() {} - - /** - * Set the model who generates the message - * - * @param \Phalcon\Mvc\ModelInterface $model - * @return Message - */ - public function setModel(\Phalcon\Mvc\ModelInterface $model) {} - - /** - * Sets code for the message - * - * @param int $code - * @return Message - */ - public function setCode($code) {} - - /** - * Returns the model that produced the message - * - * @return \Phalcon\Mvc\ModelInterface - */ - public function getModel() {} - - /** - * Returns the message code - * - * @return int - */ - public function getCode() {} - - /** - * Magic __toString method returns verbose message - * - * @return string - */ - public function __toString() {} - - /** - * Magic __set_state helps to re-build messages variable exporting - * - * @param array $message - * @return \Phalcon\Mvc\Model\MessageInterface - */ - public static function __set_state(array $message) {} - -} diff --git a/src/Phalcon/mvc/model/MessageInterface.php b/src/Phalcon/mvc/model/MessageInterface.php deleted file mode 100644 index ffdb410e..00000000 --- a/src/Phalcon/mvc/model/MessageInterface.php +++ /dev/null @@ -1,70 +0,0 @@ -Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. - * this component collect them and store for further querying by Phalcon\Mvc\Model. - * Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data.

+ * Because Phalcon\Mvc\Model requires meta-data like field names, data types, + * primary keys, etc. This component collect them and store for further + * querying by Phalcon\Mvc\Model. Phalcon\Mvc\Model\MetaData can also use + * adapters to store temporarily or permanently the meta-data. * - *

A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:

+ * A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes: * - * + * ```php * $metaData = new \Phalcon\Mvc\Model\MetaData\Memory(); * * $attributes = $metaData->getAttributes( @@ -19,7 +20,7 @@ * ); * * print_r($attributes); - * + * ``` */ abstract class MetaData implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Mvc\Model\MetaDataInterface { @@ -27,357 +28,431 @@ abstract class MetaData implements \Phalcon\Di\InjectionAwareInterface, \Phalcon const MODELS_ATTRIBUTES = 0; - const MODELS_PRIMARY_KEY = 1; + const MODELS_AUTOMATIC_DEFAULT_INSERT = 10; - const MODELS_NON_PRIMARY_KEY = 2; + const MODELS_AUTOMATIC_DEFAULT_UPDATE = 11; - const MODELS_NOT_NULL = 3; + const MODELS_COLUMN_MAP = 0; - const MODELS_DATA_TYPES = 4; + const MODELS_DATE_AT = 6; - const MODELS_DATA_TYPES_NUMERIC = 5; + const MODELS_DATE_IN = 7; - const MODELS_DATE_AT = 6; + const MODELS_DATA_TYPES = 4; - const MODELS_DATE_IN = 7; + const MODELS_DATA_TYPES_BIND = 9; - const MODELS_IDENTITY_COLUMN = 8; + const MODELS_DATA_TYPES_NUMERIC = 5; - const MODELS_DATA_TYPES_BIND = 9; + const MODELS_DEFAULT_VALUES = 12; - const MODELS_AUTOMATIC_DEFAULT_INSERT = 10; + const MODELS_EMPTY_STRING_VALUES = 13; - const MODELS_AUTOMATIC_DEFAULT_UPDATE = 11; + const MODELS_IDENTITY_COLUMN = 8; - const MODELS_DEFAULT_VALUES = 12; + const MODELS_NON_PRIMARY_KEY = 2; - const MODELS_EMPTY_STRING_VALUES = 13; + const MODELS_NOT_NULL = 3; - const MODELS_COLUMN_MAP = 0; + const MODELS_PRIMARY_KEY = 1; const MODELS_REVERSE_COLUMN_MAP = 1; + /** + * @var CacheAdapterInterface + */ + protected $adapter; + - protected $_dependencyInjector; + protected $columnMap; - protected $_strategy; + protected $container; - protected $_metaData; + protected $metaData = array(); - protected $_columnMap; + protected $strategy; /** - * Initialize the metadata for certain table + * Returns table attributes names (fields) + * + * ```php + * print_r( + * $metaData->getAttributes( + * new Robots() + * ) + * ); + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param mixed $key - * @param mixed $table - * @param mixed $schema + * @return array */ - protected final function _initialize(\Phalcon\Mvc\ModelInterface $model, $key, $table, $schema) {} + public function getAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Sets the DependencyInjector container + * Returns attributes that must be ignored from the INSERT SQL generation * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the DependencyInjector container + * ```php + * print_r( + * $metaData->getAutomaticCreateAttributes( + * new Robots() + * ) + * ); + * ``` * - * @return \Phalcon\DiInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public function getDI() {} + public function getAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Set the meta-data extraction strategy + * Returns attributes that must be ignored from the UPDATE SQL generation * - * @param \Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy - */ - public function setStrategy(\Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) {} - - /** - * Return the strategy to obtain the meta-data + * ```php + * print_r( + * $metaData->getAutomaticUpdateAttributes( + * new Robots() + * ) + * ); + * ``` * - * @return \Phalcon\Mvc\Model\MetaData\StrategyInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public function getStrategy() {} + public function getAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Reads the complete meta-data for certain model + * Returns attributes and their bind data types * - * + * ```php * print_r( - * $metaData->readMetaData( + * $metaData->getBindTypes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public final function readMetaData(\Phalcon\Mvc\ModelInterface $model) {} + public function getBindTypes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Reads meta-data for certain model + * Returns the column map if any * - * + * ```php * print_r( - * $metaData->readMetaDataIndex( - * new Robots(), - * 0 + * $metaData->getColumnMap( + * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index + * @return array */ - public final function readMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, $index) {} + public function getColumnMap(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Writes meta-data for certain model using a MODEL_ constant + * Returns attributes (which have default values) and their default values * - * + * ```php * print_r( - * $metaData->writeColumnMapIndex( - * new Robots(), - * MetaData::MODELS_REVERSE_COLUMN_MAP, - * [ - * "leName" => "name", - * ] + * $metaData->getDefaultValues( + * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index - * @param mixed $data + * @return array */ - public final function writeMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, $index, $data) {} + public function getDefaultValues(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Reads the ordered/reversed column map for certain model + * Returns attributes and their data types * - * + * ```php * print_r( - * $metaData->readColumnMap( + * $metaData->getDataTypes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public final function readColumnMap(\Phalcon\Mvc\ModelInterface $model) {} + public function getDataTypes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Reads column-map information for certain model using a MODEL_ constant + * Returns attributes which types are numerical * - * + * ```php * print_r( - * $metaData->readColumnMapIndex( - * new Robots(), - * MetaData::MODELS_REVERSE_COLUMN_MAP + * $metaData->getDataTypesNumeric( + * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index + * @return array */ - public final function readColumnMapIndex(\Phalcon\Mvc\ModelInterface $model, $index) {} + public function getDataTypesNumeric(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns table attributes names (fields) + * Returns the DependencyInjector container + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Returns attributes allow empty strings * - * + * ```php * print_r( - * $metaData->getAttributes( + * $metaData->getEmptyStringAttributes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getAttributes(\Phalcon\Mvc\ModelInterface $model) {} + public function getEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns an array of fields which are part of the primary key + * Returns the name of identity field (if one is present) * - * + * ```php * print_r( - * $metaData->getPrimaryKeyAttributes( + * $metaData->getIdentityField( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return string */ - public function getPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model) {} + public function getIdentityField(\Phalcon\Mvc\ModelInterface $model): string {} /** * Returns an array of fields which are not part of the primary key * - * + * ```php * print_r( * $metaData->getNonPrimaryKeyAttributes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getNonPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model) {} + public function getNonPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** * Returns an array of not null attributes * - * + * ```php * print_r( * $metaData->getNotNullAttributes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getNotNullAttributes(\Phalcon\Mvc\ModelInterface $model) {} + public function getNotNullAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns attributes and their data types + * Returns an array of fields which are part of the primary key * - * + * ```php * print_r( - * $metaData->getDataTypes( + * $metaData->getPrimaryKeyAttributes( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getDataTypes(\Phalcon\Mvc\ModelInterface $model) {} + public function getPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns attributes which types are numerical + * Returns the reverse column map if any * - * + * ```php * print_r( - * $metaData->getDataTypesNumeric( + * $metaData->getReverseColumnMap( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getDataTypesNumeric(\Phalcon\Mvc\ModelInterface $model) {} + public function getReverseColumnMap(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns the name of identity field (if one is present) + * Return the strategy to obtain the meta-data * - * + * @return \Phalcon\Mvc\Model\MetaData\StrategyInterface + */ + public function getStrategy(): StrategyInterface {} + + /** + * Check if a model has certain attribute + * + * ```php + * var_dump( + * $metaData->hasAttribute( + * new Robots(), + * "name" + * ) + * ); + * ``` + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param string $attribute + * @return bool + */ + public function hasAttribute(\Phalcon\Mvc\ModelInterface $model, string $attribute): bool {} + + /** + * Checks if the internal meta-data container is empty + * + * ```php + * var_dump( + * $metaData->isEmpty() + * ); + * ``` + * + * @return bool + */ + public function isEmpty(): bool {} + + /** + * Reads metadata from the adapter + * + * @param string $key + * @return array|null + */ + public function read(string $key): ?array {} + + /** + * Reads the ordered/reversed column map for certain model + * + * ```php * print_r( - * $metaData->getIdentityField( + * $metaData->readColumnMap( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @return array|null */ - public function getIdentityField(\Phalcon\Mvc\ModelInterface $model) {} + final public function readColumnMap(\Phalcon\Mvc\ModelInterface $model): ?array {} /** - * Returns attributes and their bind data types + * Reads column-map information for certain model using a MODEL_ constant * - * + * ```php * print_r( - * $metaData->getBindTypes( - * new Robots() + * $metaData->readColumnMapIndex( + * new Robots(), + * MetaData::MODELS_REVERSE_COLUMN_MAP * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param int $index */ - public function getBindTypes(\Phalcon\Mvc\ModelInterface $model) {} + final public function readColumnMapIndex(\Phalcon\Mvc\ModelInterface $model, int $index) {} /** - * Returns attributes that must be ignored from the INSERT SQL generation + * Reads the complete meta-data for certain model * - * + * ```php * print_r( - * $metaData->getAutomaticCreateAttributes( + * $metaData->readMetaData( * new Robots() * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model) {} + final public function readMetaData(\Phalcon\Mvc\ModelInterface $model): array {} /** - * Returns attributes that must be ignored from the UPDATE SQL generation + * Reads meta-data for certain model * - * + * ```php * print_r( - * $metaData->getAutomaticUpdateAttributes( - * new Robots() + * $metaData->readMetaDataIndex( + * new Robots(), + * 0 * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param int $index */ - public function getAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model) {} + final public function readMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, int $index) {} + + /** + * Resets internal meta-data in order to regenerate it + * + * ```php + * $metaData->reset(); + * ``` + */ + public function reset() {} /** * Set the attributes that must be ignored from the INSERT SQL generation * - * + * ```php * $metaData->setAutomaticCreateAttributes( * new Robots(), * [ * "created_at" => true, * ] * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @param array $attributes @@ -387,14 +462,14 @@ public function setAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model, /** * Set the attributes that must be ignored from the UPDATE SQL generation * - * + * ```php * $metaData->setAutomaticUpdateAttributes( * new Robots(), * [ * "modified_at" => true, * ] * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @param array $attributes @@ -404,14 +479,14 @@ public function setAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model, /** * Set the attributes that allow empty string values * - * + * ```php * $metaData->setEmptyStringAttributes( * new Robots(), * [ * "name" => true, * ] * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model * @param array $attributes @@ -419,107 +494,63 @@ public function setAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model, public function setEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes) {} /** - * Returns attributes allow empty strings - * - * - * print_r( - * $metaData->getEmptyStringAttributes( - * new Robots() - * ) - * ); - * + * Sets the DependencyInjector container * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param \Phalcon\Di\DiInterface $container */ - public function getEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Returns attributes (which have default values) and their default values - * - * - * print_r( - * $metaData->getDefaultValues( - * new Robots() - * ) - * ); - * + * Set the meta-data extraction strategy * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param \Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy */ - public function getDefaultValues(\Phalcon\Mvc\ModelInterface $model) {} + public function setStrategy(\Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) {} /** - * Returns the column map if any - * - * - * print_r( - * $metaData->getColumnMap( - * new Robots() - * ) - * ); - * + * Writes the metadata to adapter * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param string $key + * @param array $data */ - public function getColumnMap(\Phalcon\Mvc\ModelInterface $model) {} + public function write(string $key, array $data) {} /** - * Returns the reverse column map if any + * Writes meta-data for certain model using a MODEL_ constant * - * + * ```php * print_r( - * $metaData->getReverseColumnMap( - * new Robots() - * ) - * ); - * - * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array - */ - public function getReverseColumnMap(\Phalcon\Mvc\ModelInterface $model) {} - - /** - * Check if a model has certain attribute - * - * - * var_dump( - * $metaData->hasAttribute( + * $metaData->writeColumnMapIndex( * new Robots(), - * "name" + * MetaData::MODELS_REVERSE_COLUMN_MAP, + * [ + * "leName" => "name", + * ] * ) * ); - * + * ``` * * @param \Phalcon\Mvc\ModelInterface $model - * @param string $attribute - * @return bool + * @param int $index + * @param mixed $data */ - public function hasAttribute(\Phalcon\Mvc\ModelInterface $model, $attribute) {} + final public function writeMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, int $index, $data) {} /** - * Checks if the internal meta-data container is empty - * - * - * var_dump( - * $metaData->isEmpty() - * ); - * + * Initialize the metadata for certain table * - * @return bool + * @param \Phalcon\Mvc\ModelInterface $model + * @param mixed $key + * @param mixed $table + * @param mixed $schema */ - public function isEmpty() {} + final protected function initialize(\Phalcon\Mvc\ModelInterface $model, $key, $table, $schema) {} /** - * Resets internal meta-data in order to regenerate it + * Throws an exception when the metadata cannot be written * - * - * $metaData->reset(); - * + * @param mixed $option */ - public function reset() {} + private function throwWriteException($option) {} } diff --git a/src/Phalcon/mvc/model/MetaDataInterface.php b/src/Phalcon/mvc/model/MetaDataInterface.php index 502ec310..bea647c2 100644 --- a/src/Phalcon/mvc/model/MetaDataInterface.php +++ b/src/Phalcon/mvc/model/MetaDataInterface.php @@ -11,225 +11,225 @@ interface MetaDataInterface { /** - * Set the meta-data extraction strategy + * Returns table attributes names (fields) * - * @param \Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy + * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public function setStrategy(\Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy); + public function getAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Return the strategy to obtain the meta-data + * Returns attributes that must be ignored from the INSERT SQL generation * - * @return \Phalcon\Mvc\Model\MetaData\StrategyInterface + * @param \Phalcon\Mvc\ModelInterface $model + * @return array */ - public function getStrategy(); + public function getAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Reads meta-data for certain model + * Returns attributes that must be ignored from the UPDATE SQL generation * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function readMetaData(\Phalcon\Mvc\ModelInterface $model); + public function getAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Reads meta-data for certain model using a MODEL_ constant + * Returns attributes and their bind data types * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index - * @return mixed + * @return array */ - public function readMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, $index); + public function getBindTypes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Writes meta-data for certain model using a MODEL_ constant + * Returns the column map if any * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index - * @param mixed $data + * @return array */ - public function writeMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, $index, $data); + public function getColumnMap(\Phalcon\Mvc\ModelInterface $model): array; /** - * Reads the ordered/reversed column map for certain model + * Returns attributes (which have default values) and their default values * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function readColumnMap(\Phalcon\Mvc\ModelInterface $model); + public function getDefaultValues(\Phalcon\Mvc\ModelInterface $model): array; /** - * Reads column-map information for certain model using a MODEL_ constant + * Returns attributes and their data types * * @param \Phalcon\Mvc\ModelInterface $model - * @param int $index + * @return array */ - public function readColumnMapIndex(\Phalcon\Mvc\ModelInterface $model, $index); + public function getDataTypes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns table attributes names (fields) + * Returns attributes which types are numerical * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getAttributes(\Phalcon\Mvc\ModelInterface $model); + public function getDataTypesNumeric(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns an array of fields which are part of the primary key + * Returns attributes allow empty strings * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model); + public function getEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns an array of fields which are not part of the primary key + * Returns the name of identity field (if one is present) * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return string */ - public function getNonPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model); + public function getIdentityField(\Phalcon\Mvc\ModelInterface $model): string; /** - * Returns an array of not null attributes + * Returns an array of fields which are not part of the primary key * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getNotNullAttributes(\Phalcon\Mvc\ModelInterface $model); + public function getNonPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns attributes and their data types + * Returns an array of not null attributes * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getDataTypes(\Phalcon\Mvc\ModelInterface $model); + public function getNotNullAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns attributes which types are numerical + * Returns an array of fields which are part of the primary key * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getDataTypesNumeric(\Phalcon\Mvc\ModelInterface $model); + public function getPrimaryKeyAttributes(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns the name of identity field (if one is present) + * Returns the reverse column map if any * * @param \Phalcon\Mvc\ModelInterface $model - * @return string + * @return array */ - public function getIdentityField(\Phalcon\Mvc\ModelInterface $model); + public function getReverseColumnMap(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns attributes and their bind data types + * Return the strategy to obtain the meta-data * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return \Phalcon\Mvc\Model\MetaData\StrategyInterface */ - public function getBindTypes(\Phalcon\Mvc\ModelInterface $model); + public function getStrategy(): StrategyInterface; /** - * Returns attributes that must be ignored from the INSERT SQL generation + * Check if a model has certain attribute * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param string $attribute + * @return bool */ - public function getAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model); + public function hasAttribute(\Phalcon\Mvc\ModelInterface $model, string $attribute): bool; /** - * Returns attributes that must be ignored from the UPDATE SQL generation + * Checks if the internal meta-data container is empty * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @return bool */ - public function getAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model); + public function isEmpty(): bool; /** - * Set the attributes that must be ignored from the INSERT SQL generation + * Reads meta-data from the adapter * - * @param \Phalcon\Mvc\ModelInterface $model - * @param array $attributes + * @param string $key + * @return array|null */ - public function setAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); + public function read(string $key): ?array; /** - * Set the attributes that must be ignored from the UPDATE SQL generation + * Reads the ordered/reversed column map for certain model * * @param \Phalcon\Mvc\ModelInterface $model - * @param array $attributes + * @return array|null */ - public function setAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); + public function readColumnMap(\Phalcon\Mvc\ModelInterface $model): ?array; /** - * Set the attributes that allow empty string values + * Reads column-map information for certain model using a MODEL_ constant * * @param \Phalcon\Mvc\ModelInterface $model - * @param array $attributes + * @param int $index */ - public function setEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); + public function readColumnMapIndex(\Phalcon\Mvc\ModelInterface $model, int $index); /** - * Returns attributes allow empty strings + * Reads meta-data for certain model * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ - public function getEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model); + public function readMetaData(\Phalcon\Mvc\ModelInterface $model): array; /** - * Returns attributes (which have default values) and their default values + * Reads meta-data for certain model using a MODEL_ constant * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param int $index + * @return mixed */ - public function getDefaultValues(\Phalcon\Mvc\ModelInterface $model); + public function readMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, int $index); /** - * Returns the column map if any - * - * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * Resets internal meta-data in order to regenerate it */ - public function getColumnMap(\Phalcon\Mvc\ModelInterface $model); + public function reset(); /** - * Returns the reverse column map if any + * Set the attributes that must be ignored from the INSERT SQL generation * * @param \Phalcon\Mvc\ModelInterface $model - * @return array + * @param array $attributes */ - public function getReverseColumnMap(\Phalcon\Mvc\ModelInterface $model); + public function setAutomaticCreateAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); /** - * Check if a model has certain attribute + * Set the attributes that must be ignored from the UPDATE SQL generation * * @param \Phalcon\Mvc\ModelInterface $model - * @param string $attribute - * @return bool + * @param array $attributes */ - public function hasAttribute(\Phalcon\Mvc\ModelInterface $model, $attribute); + public function setAutomaticUpdateAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); /** - * Checks if the internal meta-data container is empty + * Set the attributes that allow empty string values * - * @return boolean + * @param \Phalcon\Mvc\ModelInterface $model + * @param array $attributes */ - public function isEmpty(); + public function setEmptyStringAttributes(\Phalcon\Mvc\ModelInterface $model, array $attributes); /** - * Resets internal meta-data in order to regenerate it + * Writes meta-data for certain model using a MODEL_ constant + * + * @param \Phalcon\Mvc\ModelInterface $model + * @param int $index + * @param mixed $data */ - public function reset(); + public function writeMetaDataIndex(\Phalcon\Mvc\ModelInterface $model, int $index, $data); /** - * Reads meta-data from the adapter + * Set the meta-data extraction strategy * - * @param string $key - * @return array + * @param \Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy */ - public function read($key); + public function setStrategy(\Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy); /** * Writes meta-data to the adapter @@ -237,6 +237,6 @@ public function read($key); * @param string $key * @param array $data */ - public function write($key, $data); + public function write(string $key, array $data); } diff --git a/src/Phalcon/mvc/model/Query.php b/src/Phalcon/mvc/model/Query.php index dd7594e6..5d33d3c1 100644 --- a/src/Phalcon/mvc/model/Query.php +++ b/src/Phalcon/mvc/model/Query.php @@ -7,7 +7,7 @@ * * This class takes a PHQL intermediate representation and executes it. * - * + * ```php * $phql = "SELECT c.price0.16 AS taxes, c. FROM Cars AS c JOIN Brands AS b * WHERE b.name = :name: ORDER BY c.name"; * @@ -49,103 +49,107 @@ * $resultWithEntries = $queryWithTransaction->execute(); * * $queryWithOutTransaction = new Query($phql, $di); - * $resultWithOutEntries = $queryWithTransaction->execute() - * - * + * $resultWithOutEntries = $queryWithTransaction->execute(); + * ``` */ class Query implements \Phalcon\Mvc\Model\QueryInterface, \Phalcon\Di\InjectionAwareInterface { - const TYPE_SELECT = 309; + const TYPE_DELETE = 303; const TYPE_INSERT = 306; + const TYPE_SELECT = 309; + + const TYPE_UPDATE = 300; - const TYPE_DELETE = 303; + protected $ast; + + protected $bindParams; - protected $_dependencyInjector; + protected $bindTypes; - protected $_manager; + protected $cache; - protected $_metaData; + protected $cacheOptions; - protected $_type; + protected $container; - protected $_phql; + protected $enableImplicitJoins; - protected $_ast; + protected $intermediate; - protected $_intermediate; + protected $manager; - protected $_models; + protected $metaData; - protected $_sqlAliases; + protected $models; - protected $_sqlAliasesModels; + protected $modelsInstances; - protected $_sqlModelsAliases; + protected $nestingLevel = -1; - protected $_sqlAliasesModelsInstances; + protected $phql; - protected $_sqlColumnAliases; + protected $sharedLock; - protected $_modelsInstances; + protected $sqlAliases; - protected $_cache; + protected $sqlAliasesModels; - protected $_cacheOptions; + protected $sqlAliasesModelsInstances; - protected $_uniqueRow; + protected $sqlColumnAliases = array(); - protected $_bindParams; + protected $sqlModelsAliases; - protected $_bindTypes; + protected $type; - protected $_enableImplicitJoins; + protected $uniqueRow; - protected $_sharedLock; + + static protected $_irPhqlCache; /** * TransactionInterface so that the query can wrap a transaction * around batch updates and intermediate selects within the transaction. - * however if a model got a transaction set inside it will use the local transaction instead of this one + * however if a model got a transaction set inside it will use the local + * transaction instead of this one */ protected $_transaction; - static protected $_irPhqlCache; - - /** * TransactionInterface so that the query can wrap a transaction * * around batch updates and intermediate selects within the transaction. - * however if a model got a transaction set inside it will use the local transaction instead of this one + * however if a model got a transaction set inside it will use the local + * transaction instead of this one */ public function getTransaction() {} @@ -153,47 +157,50 @@ public function getTransaction() {} * Phalcon\Mvc\Model\Query constructor * * @param string $phql - * @param \Phalcon\DiInterface $dependencyInjector - * @param mixed $options + * @param \Phalcon\Di\DiInterface $container + * @param array $options */ - public function __construct($phql = null, \Phalcon\DiInterface $dependencyInjector = null, $options = null) {} + public function __construct(string $phql = null, \Phalcon\Di\DiInterface $container = null, array $options = array()) {} /** * Sets the dependency injection container * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** * Returns the dependency injection container * - * @return \Phalcon\DiInterface + * @return \Phalcon\Di\DiInterface */ - public function getDI() {} + public function getDI(): DiInterface {} /** - * Tells to the query if only the first row in the resultset must be returned + * Tells to the query if only the first row in the resultset must be + * returned * * @param bool $uniqueRow - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setUniqueRow($uniqueRow) {} + public function setUniqueRow(bool $uniqueRow): QueryInterface {} /** - * Check if the query is programmed to get only the first row in the resultset + * Check if the query is programmed to get only the first row in the + * resultset * * @return bool */ - public function getUniqueRow() {} + public function getUniqueRow(): bool {} /** - * Replaces the model's name to its source name in a qualified-name expression + * Replaces the model's name to its source name in a qualified-name + * expression * * @param array $expr * @return array */ - protected final function _getQualified(array $expr) {} + final protected function _getQualified(array $expr): array {} /** * Resolves an expression in a single call argument @@ -201,7 +208,7 @@ protected final function _getQualified(array $expr) {} * @param array $argument * @return array */ - protected final function _getCallArgument(array $argument) {} + final protected function _getCallArgument(array $argument): array {} /** * Resolves an expression in a single call argument @@ -209,7 +216,7 @@ protected final function _getCallArgument(array $argument) {} * @param array $expr * @return array */ - protected final function _getCaseExpression(array $expr) {} + final protected function _getCaseExpression(array $expr): array {} /** * Resolves an expression in a single call argument @@ -217,25 +224,25 @@ protected final function _getCaseExpression(array $expr) {} * @param array $expr * @return array */ - protected final function _getFunctionCall(array $expr) {} + final protected function _getFunctionCall(array $expr): array {} /** * Resolves an expression from its intermediate code into a string * * @param array $expr - * @param boolean $quoting + * @param bool $quoting * @return string */ - protected final function _getExpression($expr, $quoting = true) {} + final protected function _getExpression(array $expr, bool $quoting = true): string {} /** - * Resolves a column from its intermediate representation into an array used to determine - * if the resultset produced is simple or complex + * Resolves a column from its intermediate representation into an array + * used to determine if the resultset produced is simple or complex * * @param array $column * @return array */ - protected final function _getSelectColumn(array $column) {} + final protected function _getSelectColumn(array $column): array {} /** * Resolves a table in a SELECT statement checking if the model exists @@ -244,16 +251,16 @@ protected final function _getSelectColumn(array $column) {} * @param array $qualifiedName * @return string */ - protected final function _getTable(\Phalcon\Mvc\Model\ManagerInterface $manager, $qualifiedName) {} + final protected function _getTable(\Phalcon\Mvc\Model\ManagerInterface $manager, array $qualifiedName) {} /** * Resolves a JOIN clause checking if the associated models exist * * @param \Phalcon\Mvc\Model\ManagerInterface $manager - * @param mixed $join + * @param array $join * @return array */ - protected final function _getJoin(\Phalcon\Mvc\Model\ManagerInterface $manager, $join) {} + final protected function _getJoin(\Phalcon\Mvc\Model\ManagerInterface $manager, array $join): array {} /** * Resolves a JOIN type @@ -261,7 +268,7 @@ protected final function _getJoin(\Phalcon\Mvc\Model\ManagerInterface $manager, * @param array $join * @return string */ - protected final function _getJoinType($join) {} + final protected function _getJoinType(array $join): string {} /** * Resolves joins involving has-one/belongs-to/has-many relations @@ -273,7 +280,7 @@ protected final function _getJoinType($join) {} * @param \Phalcon\Mvc\Model\RelationInterface $relation * @return array */ - protected final function _getSingleJoin($joinType, $joinSource, $modelAlias, $joinAlias, \Phalcon\Mvc\Model\RelationInterface $relation) {} + final protected function _getSingleJoin(string $joinType, $joinSource, string $modelAlias, string $joinAlias, \Phalcon\Mvc\Model\RelationInterface $relation): array {} /** * Resolves joins involving many-to-many relations @@ -285,15 +292,16 @@ protected final function _getSingleJoin($joinType, $joinSource, $modelAlias, $jo * @param \Phalcon\Mvc\Model\RelationInterface $relation * @return array */ - protected final function _getMultiJoin($joinType, $joinSource, $modelAlias, $joinAlias, \Phalcon\Mvc\Model\RelationInterface $relation) {} + final protected function _getMultiJoin(string $joinType, $joinSource, string $modelAlias, string $joinAlias, \Phalcon\Mvc\Model\RelationInterface $relation): array {} /** - * Processes the JOINs in the query returning an internal representation for the database dialect + * Processes the JOINs in the query returning an internal representation for + * the database dialect * * @param array $select * @return array */ - protected final function _getJoins($select) {} + final protected function _getJoins(array $select): array {} /** * Returns a processed order clause for a SELECT statement @@ -301,7 +309,7 @@ protected final function _getJoins($select) {} * @param array|string $order * @return array */ - protected final function _getOrderClause($order) {} + final protected function _getOrderClause($order): array {} /** * Returns a processed group clause for a SELECT statement @@ -309,7 +317,7 @@ protected final function _getOrderClause($order) {} * @param array $group * @return array */ - protected final function _getGroupClause(array $group) {} + final protected function _getGroupClause(array $group): array {} /** * Returns a processed limit clause for a SELECT statement @@ -317,96 +325,104 @@ protected final function _getGroupClause(array $group) {} * @param array $limitClause * @return array */ - protected final function _getLimitClause(array $limitClause) {} + final protected function _getLimitClause(array $limitClause): array {} /** * Analyzes a SELECT intermediate code and produces an array to be executed later * * @param mixed $ast - * @param mixed $merge + * @param bool $merge * @return array */ - protected final function _prepareSelect($ast = null, $merge = null) {} + final protected function _prepareSelect($ast = null, bool $merge = false): array {} /** - * Analyzes an INSERT intermediate code and produces an array to be executed later + * Analyzes an INSERT intermediate code and produces an array to be executed + * later * * @return array */ - protected final function _prepareInsert() {} + final protected function _prepareInsert(): array {} /** - * Analyzes an UPDATE intermediate code and produces an array to be executed later + * Analyzes an UPDATE intermediate code and produces an array to be executed + * later * * @return array */ - protected final function _prepareUpdate() {} + final protected function _prepareUpdate(): array {} /** - * Analyzes a DELETE intermediate code and produces an array to be executed later + * Analyzes a DELETE intermediate code and produces an array to be executed + * later * * @return array */ - protected final function _prepareDelete() {} + final protected function _prepareDelete(): array {} /** - * Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another - * intermediate representation that could be executed by Phalcon\Mvc\Model\Query + * Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang + * generating another intermediate representation that could be executed by + * Phalcon\Mvc\Model\Query * * @return array */ - public function parse() {} + public function parse(): array {} /** * Returns the current cache backend instance * - * @return \Phalcon\Cache\BackendInterface + * @return \Phalcon\Cache\Adapter\AdapterInterface */ - public function getCache() {} + public function getCache(): AdapterInterface {} /** - * Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset + * Executes the SELECT intermediate representation producing a + * Phalcon\Mvc\Model\Resultset * - * @param mixed $intermediate - * @param mixed $bindParams - * @param mixed $bindTypes + * @param array $intermediate + * @param array $bindParams + * @param array $bindTypes * @param bool $simulate * @return array|\Phalcon\Mvc\Model\ResultsetInterface */ - protected final function _executeSelect($intermediate, $bindParams, $bindTypes, $simulate = false) {} + final protected function _executeSelect(array $intermediate, array $bindParams, array $bindTypes, bool $simulate = false) {} /** - * Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status + * Executes the INSERT intermediate representation producing a + * Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return \Phalcon\Mvc\Model\Query\StatusInterface */ - protected final function _executeInsert($intermediate, $bindParams, $bindTypes) {} + final protected function _executeInsert(array $intermediate, array $bindParams, array $bindTypes): StatusInterface {} /** - * Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status + * Executes the UPDATE intermediate representation producing a + * Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return \Phalcon\Mvc\Model\Query\StatusInterface */ - protected final function _executeUpdate($intermediate, $bindParams, $bindTypes) {} + final protected function _executeUpdate(array $intermediate, array $bindParams, array $bindTypes): StatusInterface {} /** - * Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status + * Executes the DELETE intermediate representation producing a + * Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return \Phalcon\Mvc\Model\Query\StatusInterface */ - protected final function _executeDelete($intermediate, $bindParams, $bindTypes) {} + final protected function _executeDelete(array $intermediate, array $bindParams, array $bindTypes): StatusInterface {} /** - * Query the records on which the UPDATE/DELETE operation well be done + * Query the records on which the UPDATE/DELETE operation will be done * * @param \Phalcon\Mvc\ModelInterface $model * @param array $intermediate @@ -414,7 +430,7 @@ protected final function _executeDelete($intermediate, $bindParams, $bindTypes) * @param array $bindTypes * @return \Phalcon\Mvc\Model\ResultsetInterface */ - protected final function _getRelatedRecords(\Phalcon\Mvc\ModelInterface $model, $intermediate, $bindParams, $bindTypes) {} + final protected function _getRelatedRecords(\Phalcon\Mvc\ModelInterface $model, array $intermediate, array $bindParams, array $bindTypes): ResultsetInterface {} /** * Executes a parsed PHQL statement @@ -423,7 +439,7 @@ protected final function _getRelatedRecords(\Phalcon\Mvc\ModelInterface $model, * @param array $bindTypes * @return mixed */ - public function execute($bindParams = null, $bindTypes = null) {} + public function execute(array $bindParams = array(), array $bindTypes = array()) {} /** * Executes the query returning the first result @@ -432,99 +448,100 @@ public function execute($bindParams = null, $bindTypes = null) {} * @param array $bindTypes * @return \Phalcon\Mvc\ModelInterface */ - public function getSingleResult($bindParams = null, $bindTypes = null) {} + public function getSingleResult(array $bindParams = array(), array $bindTypes = array()): ModelInterface {} /** * Sets the type of PHQL statement to be executed * * @param int $type - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setType($type) {} + public function setType(int $type): QueryInterface {} /** * Gets the type of PHQL statement executed * * @return int */ - public function getType() {} + public function getType(): int {} /** * Set default bind parameters * * @param array $bindParams * @param bool $merge - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setBindParams(array $bindParams, $merge = false) {} + public function setBindParams(array $bindParams, bool $merge = false): QueryInterface {} /** * Returns default bind params * * @return array */ - public function getBindParams() {} + public function getBindParams(): array {} /** * Set default bind parameters * * @param array $bindTypes * @param bool $merge - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setBindTypes(array $bindTypes, $merge = false) {} + public function setBindTypes(array $bindTypes, bool $merge = false): QueryInterface {} /** * Set SHARED LOCK clause * * @param bool $sharedLock - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setSharedLock($sharedLock = false) {} + public function setSharedLock(bool $sharedLock = false): QueryInterface {} /** * Returns default bind types * * @return array */ - public function getBindTypes() {} + public function getBindTypes(): array {} /** * Allows to set the IR to be executed * * @param array $intermediate - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setIntermediate(array $intermediate) {} + public function setIntermediate(array $intermediate): QueryInterface {} /** * Returns the intermediate representation of the PHQL statement * * @return array */ - public function getIntermediate() {} + public function getIntermediate(): array {} /** * Sets the cache parameters of the query * - * @param mixed $cacheOptions - * @return Query + * @param array $cacheOptions + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function cache($cacheOptions) {} + public function cache(array $cacheOptions): QueryInterface {} /** * Returns the current cache options * - * @param array + * @return array */ - public function getCacheOptions() {} + public function getCacheOptions(): array {} /** - * Returns the SQL to be generated by the internal PHQL (only works in SELECT statements) + * Returns the SQL to be generated by the internal PHQL (only works in + * SELECT statements) * * @return array */ - public function getSql() {} + public function getSql(): array {} /** * Destroys the internal PHQL cache @@ -532,33 +549,35 @@ public function getSql() {} public static function clean() {} /** - * Gets the read connection from the model if there is no transaction set inside the query object + * Gets the read connection from the model if there is no transaction set + * inside the query object * * @param \Phalcon\Mvc\ModelInterface $model * @param array $intermediate * @param array $bindParams * @param array $bindTypes - * @return \Phalcon\Db\AdapterInterface + * @return \Phalcon\Cache\Adapter\AdapterInterface */ - protected function getReadConnection(\Phalcon\Mvc\ModelInterface $model, array $intermediate = null, array $bindParams = null, array $bindTypes = null) {} + protected function getReadConnection(\Phalcon\Mvc\ModelInterface $model, array $intermediate = null, array $bindParams = array(), array $bindTypes = array()): AdapterInterface {} /** - * Gets the write connection from the model if there is no transaction inside the query object + * Gets the write connection from the model if there is no transaction + * inside the query object * * @param \Phalcon\Mvc\ModelInterface $model * @param array $intermediate * @param array $bindParams * @param array $bindTypes - * @return \Phalcon\Db\AdapterInterface + * @return \Phalcon\Cache\Adapter\AdapterInterface */ - protected function getWriteConnection(\Phalcon\Mvc\ModelInterface $model, array $intermediate = null, array $bindParams = null, array $bindTypes = null) {} + protected function getWriteConnection(\Phalcon\Mvc\ModelInterface $model, array $intermediate = null, array $bindParams = array(), array $bindTypes = array()): AdapterInterface {} /** * allows to wrap a transaction around all queries * * @param \Phalcon\Mvc\Model\TransactionInterface $transaction - * @return Query + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} + public function setTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction): QueryInterface {} } diff --git a/src/Phalcon/mvc/model/QueryInterface.php b/src/Phalcon/mvc/model/QueryInterface.php index 197dbcd6..80c28f29 100644 --- a/src/Phalcon/mvc/model/QueryInterface.php +++ b/src/Phalcon/mvc/model/QueryInterface.php @@ -11,50 +11,106 @@ interface QueryInterface { /** - * Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another - * intermediate representation that could be executed by Phalcon\Mvc\Model\Query + * Sets the cache parameters of the query * - * @return array + * @param array $cacheOptions + * @return QueryInterface */ - public function parse(); + public function cache(array $cacheOptions): QueryInterface; /** - * Sets the cache parameters of the query + * Executes a parsed PHQL statement * - * @param array $cacheOptions - * @return \Phalcon\Mvc\Model\Query + * @param array $bindParams + * @param array $bindTypes + * @return mixed + */ + public function execute(array $bindParams = array(), array $bindTypes = array()); + + /** + * Returns default bind params + * + * @return array */ - public function cache($cacheOptions); + public function getBindParams(): array; /** * Returns the current cache options * - * @param array + * @return array */ - public function getCacheOptions(); + public function getCacheOptions(): array; /** - * Tells to the query if only the first row in the resultset must be returned + * Returns default bind types + * + * @return array + */ + public function getBindTypes(): array; + + /** + * Returns the SQL to be generated by the internal PHQL (only works in SELECT statements) + * + * @return array + */ + public function getSql(): array; + + /** + * Executes the query returning the first result * - * @param boolean $uniqueRow - * @return \Phalcon\Mvc\Model\Query + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\ModelInterface */ - public function setUniqueRow($uniqueRow); + public function getSingleResult(array $bindParams = array(), array $bindTypes = array()): ModelInterface; /** * Check if the query is programmed to get only the first row in the resultset * - * @return boolean + * @return bool */ - public function getUniqueRow(); + public function getUniqueRow(): bool; /** - * Executes a parsed PHQL statement + * Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another + * intermediate representation that could be executed by Phalcon\Mvc\Model\Query + * + * @return array + */ + public function parse(): array; + + /** + * Set default bind parameters * * @param array $bindParams + * @param bool $merge + * @return QueryInterface + */ + public function setBindParams(array $bindParams, bool $merge = false): QueryInterface; + + /** + * Set default bind parameters + * * @param array $bindTypes - * @return mixed + * @param bool $merge + * @return QueryInterface + */ + public function setBindTypes(array $bindTypes, bool $merge = false): QueryInterface; + + /** + * Set SHARED LOCK clause + * + * @param bool $sharedLock + * @return QueryInterface + */ + public function setSharedLock(bool $sharedLock = false): QueryInterface; + + /** + * Tells to the query if only the first row in the resultset must be returned + * + * @param bool $uniqueRow + * @return QueryInterface */ - public function execute($bindParams = null, $bindTypes = null); + public function setUniqueRow(bool $uniqueRow): QueryInterface; } diff --git a/src/Phalcon/mvc/model/Relation.php b/src/Phalcon/mvc/model/Relation.php index 362d73ff..4284bf95 100644 --- a/src/Phalcon/mvc/model/Relation.php +++ b/src/Phalcon/mvc/model/Relation.php @@ -10,52 +10,52 @@ class Relation implements \Phalcon\Mvc\Model\RelationInterface { - const BELONGS_TO = 0; + const ACTION_CASCADE = 2; - const HAS_ONE = 1; + const ACTION_RESTRICT = 1; - const HAS_MANY = 2; + const BELONGS_TO = 0; - const HAS_ONE_THROUGH = 3; + const HAS_MANY = 2; const HAS_MANY_THROUGH = 4; - const NO_ACTION = 0; + const HAS_ONE = 1; - const ACTION_RESTRICT = 1; + const HAS_ONE_THROUGH = 3; - const ACTION_CASCADE = 2; + const NO_ACTION = 0; - protected $_type; + protected $fields; - protected $_referencedModel; + protected $intermediateFields; - protected $_fields; + protected $intermediateModel; - protected $_referencedFields; + protected $intermediateReferencedFields; - protected $_intermediateModel; + protected $options; - protected $_intermediateFields; + protected $referencedFields; - protected $_intermediateReferencedFields; + protected $referencedModel; - protected $_options; + protected $type; /** @@ -67,51 +67,42 @@ class Relation implements \Phalcon\Mvc\Model\RelationInterface * @param string|array $referencedFields * @param array $options */ - public function __construct($type, $referencedModel, $fields, $referencedFields, $options = null) {} - - /** - * Sets the intermediate model data for has--through relations - * - * @param string|array $intermediateFields - * @param string $intermediateModel - * @param string $intermediateReferencedFields - */ - public function setIntermediateRelation($intermediateFields, $intermediateModel, $intermediateReferencedFields) {} + public function __construct(int $type, string $referencedModel, $fields, $referencedFields, array $options = array()) {} /** - * Returns the relation type + * Returns the fields * - * @return int + * @return string|array */ - public function getType() {} + public function getFields() {} /** - * Returns the referenced model + * Returns the foreign key configuration * - * @return string + * @return string|array */ - public function getReferencedModel() {} + public function getForeignKey() {} /** - * Returns the fields + * Gets the intermediate fields for has--through relations * * @return string|array */ - public function getFields() {} + public function getIntermediateFields() {} /** - * Returns the referenced fields + * Gets the intermediate model for has--through relations * - * @return string|array + * @return string */ - public function getReferencedFields() {} + public function getIntermediateModel(): string {} /** - * Returns the options + * Gets the intermediate referenced fields for has--through relations * * @return string|array */ - public function getOptions() {} + public function getIntermediateReferencedFields() {} /** * Returns an option by the specified name @@ -119,62 +110,71 @@ public function getOptions() {} * * @param string $name */ - public function getOption($name) {} + public function getOption(string $name) {} /** - * Check whether the relation act as a foreign key + * Returns the options * - * @return bool + * @return array */ - public function isForeignKey() {} + public function getOptions(): array {} /** - * Returns the foreign key configuration + * Returns parameters that must be always used when the related records are obtained * - * @return string|array + * @return array */ - public function getForeignKey() {} + public function getParams() {} /** - * Returns parameters that must be always used when the related records are obtained + * Returns the relation type * - * @return array + * @return int */ - public function getParams() {} + public function getType(): int {} /** - * Check whether the relation is a 'many-to-many' relation or not + * Returns the referenced fields * - * @return bool + * @return string|array */ - public function isThrough() {} + public function getReferencedFields() {} /** - * Check if records returned by getting belongs-to/has-many are implicitly cached during the current request + * Returns the referenced model + * + * @return string + */ + public function getReferencedModel(): string {} + + /** + * Check whether the relation act as a foreign key * * @return bool */ - public function isReusable() {} + public function isForeignKey(): bool {} /** - * Gets the intermediate fields for has--through relations + * Check whether the relation is a 'many-to-many' relation or not * - * @return string|array + * @return bool */ - public function getIntermediateFields() {} + public function isThrough(): bool {} /** - * Gets the intermediate model for has--through relations + * Check if records returned by getting belongs-to/has-many are implicitly cached during the current request * - * @return string + * @return bool */ - public function getIntermediateModel() {} + public function isReusable(): bool {} /** - * Gets the intermediate referenced fields for has--through relations + * Sets the intermediate model data for has--through relations * - * @return string|array + * @param string|array $intermediateFields + * @param string $intermediateModel + * @param string $intermediateReferencedFields */ - public function getIntermediateReferencedFields() {} + public function setIntermediateRelation($intermediateFields, string $intermediateModel, $intermediateReferencedFields) {} } diff --git a/src/Phalcon/mvc/model/RelationInterface.php b/src/Phalcon/mvc/model/RelationInterface.php index 992893d1..4f018af5 100644 --- a/src/Phalcon/mvc/model/RelationInterface.php +++ b/src/Phalcon/mvc/model/RelationInterface.php @@ -11,104 +11,111 @@ interface RelationInterface { /** - * Sets the intermediate model dat for has--through relations + * Returns the fields * - * @param string|array $intermediateFields - * @param string $intermediateModel - * @param string|array $intermediateReferencedFields + * @return string|array */ - public function setIntermediateRelation($intermediateFields, $intermediateModel, $intermediateReferencedFields); + public function getFields(); /** - * Check if records returned by getting belongs-to/has-many are implicitly cached during the current request + * Returns the foreign key configuration * - * @return bool + * @return string|array */ - public function isReusable(); + public function getForeignKey(); /** - * Returns the relations type + * Gets the intermediate fields for has--through relations * - * @return int + * @return string|array */ - public function getType(); + public function getIntermediateFields(); /** - * Returns the referenced model + * Gets the intermediate model for has--through relations * * @return string */ - public function getReferencedModel(); + public function getIntermediateModel(): string; /** - * Returns the fields + * Gets the intermediate referenced fields for has--through relations * * @return string|array */ - public function getFields(); + public function getIntermediateReferencedFields(); /** - * Returns the referenced fields + * Returns an option by the specified name + * If the option doesn't exist null is returned * - * @return string|array + * @param string $name */ - public function getReferencedFields(); + public function getOption(string $name); /** * Returns the options * - * @return string|array + * @return array */ - public function getOptions(); + public function getOptions(): array; /** - * Returns an option by the specified name - * If the option doesn't exist null is returned + * Returns parameters that must be always used when the related records are obtained * - * @param string $name + * @return array */ - public function getOption($name); + public function getParams(); /** - * Check whether the relation act as a foreign key + * Returns the referenced fields * - * @return bool + * @return string|array */ - public function isForeignKey(); + public function getReferencedFields(); /** - * Returns the foreign key configuration + * Returns the referenced model * - * @return string|array + * @return string */ - public function getForeignKey(); + public function getReferencedModel(): string; /** - * Check whether the relation is a 'many-to-many' relation or not + * Returns the relations type + * + * @return int + */ + public function getType(): int; + + /** + * Check whether the relation act as a foreign key * * @return bool */ - public function isThrough(); + public function isForeignKey(): bool; /** - * Gets the intermediate fields for has--through relations + * Check if records returned by getting belongs-to/has-many are implicitly cached during the current request * - * @return string|array + * @return bool */ - public function getIntermediateFields(); + public function isReusable(): bool; /** - * Gets the intermediate model for has--through relations + * Check whether the relation is a 'many-to-many' relation or not * - * @return string + * @return bool */ - public function getIntermediateModel(); + public function isThrough(): bool; /** - * Gets the intermediate referenced fields for has--through relations + * Sets the intermediate model dat for has--through relations * - * @return string|array + * @param string|array $intermediateFields + * @param string $intermediateModel + * @param string|array $intermediateReferencedFields */ - public function getIntermediateReferencedFields(); + public function setIntermediateRelation($intermediateFields, string $intermediateModel, $intermediateReferencedFields); } diff --git a/src/Phalcon/mvc/model/ResultInterface.php b/src/Phalcon/mvc/model/ResultInterface.php index 12423705..9ba8f10b 100644 --- a/src/Phalcon/mvc/model/ResultInterface.php +++ b/src/Phalcon/mvc/model/ResultInterface.php @@ -13,8 +13,9 @@ interface ResultInterface /** * Sets the object's state * - * @param integer $dirtyState + * @param int $dirtyState + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function setDirtyState($dirtyState); + public function setDirtyState(int $dirtyState); } diff --git a/src/Phalcon/mvc/model/Resultset.php b/src/Phalcon/mvc/model/Resultset.php index 5e2e1bb8..4064c4a7 100644 --- a/src/Phalcon/mvc/model/Resultset.php +++ b/src/Phalcon/mvc/model/Resultset.php @@ -10,7 +10,7 @@ * it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before * serializing. * - * + * ```php * * // Using a standard foreach * $robots = Robots::find( @@ -41,247 +41,248 @@ * * $robots->next(); * } - * + * ``` */ abstract class Resultset implements \Phalcon\Mvc\Model\ResultsetInterface, \Iterator, \SeekableIterator, \Countable, \ArrayAccess, \Serializable, \JsonSerializable { - const TYPE_RESULT_FULL = 0; + const HYDRATE_ARRAYS = 1; - const TYPE_RESULT_PARTIAL = 1; + const HYDRATE_OBJECTS = 2; const HYDRATE_RECORDS = 0; - const HYDRATE_OBJECTS = 2; + const TYPE_RESULT_FULL = 0; - const HYDRATE_ARRAYS = 1; + const TYPE_RESULT_PARTIAL = 1; - /** - * Phalcon\Db\ResultInterface or false for empty resultset - */ - protected $_result = false; + protected $activeRow = null; - protected $_cache; + protected $cache; - protected $_isFresh = true; + protected $count; - protected $_pointer = 0; + protected $errorMessages; - protected $_count; + protected $hydrateMode = 0; - protected $_activeRow = null; + protected $isFresh = true; - protected $_rows = null; + protected $pointer = 0; - protected $_row = null; + protected $row = null; - protected $_errorMessages; + protected $rows = null; - protected $_hydrateMode = 0; + /** + * Phalcon\Db\ResultInterface or false for empty resultset + */ + protected $result; /** * Phalcon\Mvc\Model\Resultset constructor * * @param \Phalcon\Db\ResultInterface|false $result - * @param \Phalcon\Cache\BackendInterface $cache + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache */ - public function __construct($result, \Phalcon\Cache\BackendInterface $cache = null) {} + public function __construct($result, \Phalcon\Cache\Adapter\AdapterInterface $cache = null) {} /** - * Moves cursor to next row in the resultset + * Counts how many rows are in the resultset + * + * @return int */ - public function next() {} + final public function count(): int {} /** - * Check whether internal resource has rows to fetch + * Deletes every record in the resultset * + * @param \Closure $conditionCallback * @return bool */ - public function valid() {} + public function delete(\Closure $conditionCallback = null): bool {} /** - * Gets pointer number of active row in the resultset + * Filters a resultset returning only those the developer requires * - * @return int|null + * ```php + * $filtered = $robots->filter( + * function ($robot) { + * if ($robot->id < 3) { + * return $robot; + * } + * } + * ); + * ``` + * + * @param callable $filter + * @return array|\Phalcon\Mvc\ModelInterface[] */ - public function key() {} + public function filter($filter): array {} /** - * Rewinds resultset to its beginning + * Returns the associated cache for the resultset + * + * @return \Phalcon\Cache\Adapter\AdapterInterface */ - public final function rewind() {} + public function getCache(): AdapterInterface {} /** - * Changes the internal pointer to a specific position in the resultset. - * Set the new position if required, and then set this->_row + * Get first row in the resultset * - * @param mixed $position + * @return null|\Phalcon\Mvc\ModelInterface */ - public final function seek($position) {} + public function getFirst(): ?ModelInterface {} /** - * Counts how many rows are in the resultset + * Returns the current hydration mode * * @return int */ - public final function count() {} + public function getHydrateMode(): int {} /** - * Checks whether offset exists in the resultset + * Get last row in the resultset * - * @param mixed $index - * @return bool + * @return null|\Phalcon\Mvc\ModelInterface */ - public function offsetExists($index) {} + public function getLast(): ?ModelInterface {} /** - * Gets row in a specific position of the resultset + * Returns the error messages produced by a batch operation * - * @param mixed $index - * @return bool|\Phalcon\Mvc\ModelInterface + * @return array|\Phalcon\Messages\MessageInterface[] */ - public function offsetGet($index) {} + public function getMessages(): array {} /** - * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + * Returns the internal type of data retrieval that the resultset is using * - * @param int $index - * @param \Phalcon\Mvc\ModelInterface $value + * @return int */ - public function offsetSet($index, $value) {} + public function getType(): int {} /** - * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + * Tell if the resultset if fresh or an old one cached * - * @param mixed $offset + * @return bool */ - public function offsetUnset($offset) {} + public function isFresh(): bool {} /** - * Returns the internal type of data retrieval that the resultset is using + * Returns serialised model objects as array for json_encode. + * Calls jsonSerialize on each object if present * - * @return int + * ```php + * $robots = Robots::find(); + * + * echo json_encode($robots); + * ``` + * + * @return array */ - public function getType() {} + public function jsonSerialize(): array {} /** - * Get first row in the resultset + * Gets pointer number of active row in the resultset * - * @return bool|\Phalcon\Mvc\ModelInterface + * @return int|null */ - public function getFirst() {} + public function key(): ?int {} /** - * Get last row in the resultset - * - * @return bool|\Phalcon\Mvc\ModelInterface + * Moves cursor to next row in the resultset */ - public function getLast() {} + public function next() {} /** - * Set if the resultset is fresh or an old one cached + * Gets row in a specific position of the resultset * - * @param bool $isFresh - * @return Resultset + * @param mixed $index + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function setIsFresh($isFresh) {} + public function offsetGet($index) {} /** - * Tell if the resultset if fresh or an old one cached + * Checks whether offset exists in the resultset * + * @param mixed $index * @return bool */ - public function isFresh() {} + public function offsetExists($index): bool {} /** - * Sets the hydration mode in the resultset + * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface * - * @param int $hydrateMode - * @return Resultset + * @param int $index + * @param \Phalcon\Mvc\ModelInterface $value */ - public function setHydrateMode($hydrateMode) {} + public function offsetSet($index, $value) {} /** - * Returns the current hydration mode + * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface * - * @return int + * @param mixed $offset */ - public function getHydrateMode() {} + public function offsetUnset($offset) {} /** - * Returns the associated cache for the resultset - * - * @return \Phalcon\Cache\BackendInterface + * Rewinds resultset to its beginning */ - public function getCache() {} + final public function rewind() {} /** - * Returns the error messages produced by a batch operation + * Changes the internal pointer to a specific position in the resultset. + * Set the new position if required, and then set this->row * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @param mixed $position */ - public function getMessages() {} + final public function seek($position) {} /** - * Updates every record in the resultset + * Sets the hydration mode in the resultset * - * @param array $data - * @param \Closure $conditionCallback - * @return bool + * @param int $hydrateMode + * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public function update($data, \Closure $conditionCallback = null) {} + public function setHydrateMode(int $hydrateMode): ResultsetInterface {} /** - * Deletes every record in the resultset + * Set if the resultset is fresh or an old one cached * - * @param \Closure $conditionCallback - * @return bool + * @param bool $isFresh + * @return \Phalcon\Mvc\Model\ResultsetInterface */ - public function delete(\Closure $conditionCallback = null) {} + public function setIsFresh(bool $isFresh): ResultsetInterface {} /** - * Filters a resultset returning only those the developer requires - * - * - * $filtered = $robots->filter( - * function ($robot) { - * if ($robot->id < 3) { - * return $robot; - * } - * } - * ); - * + * Updates every record in the resultset * - * @param callback $filter - * @return array + * @param array $data + * @param \Closure $conditionCallback + * @return bool */ - public function filter($filter) {} + public function update($data, \Closure $conditionCallback = null): bool {} /** - * Returns serialised model objects as array for json_encode. - * Calls jsonSerialize on each object if present - * - * - * $robots = Robots::find(); - * echo json_encode($robots); - * + * Check whether internal resource has rows to fetch * - * @return array + * @return bool */ - public function jsonSerialize() {} + public function valid(): bool {} } diff --git a/src/Phalcon/mvc/model/ResultsetInterface.php b/src/Phalcon/mvc/model/ResultsetInterface.php index f1252a35..b36b34d7 100644 --- a/src/Phalcon/mvc/model/ResultsetInterface.php +++ b/src/Phalcon/mvc/model/ResultsetInterface.php @@ -11,46 +11,95 @@ interface ResultsetInterface { /** - * Returns the internal type of data retrieval that the resultset is using + * Deletes every record in the resultset * - * @return int + * @param \Closure $conditionCallback + * @return bool + */ + public function delete(\Closure $conditionCallback = null): bool; + + /** + * Filters a resultset returning only those the developer requires + * + * ```php + * $filtered = $robots->filter( + * function ($robot) { + * if ($robot->id < 3) { + * return $robot; + * } + * } + * ); + * ``` + * + * @param callable $filter + * @return array|\Phalcon\Mvc\ModelInterface[] */ - public function getType(); + public function filter($filter): array; + + /** + * Returns the associated cache for the resultset + * + * @return \Phalcon\Cache\Adapter\AdapterInterface + */ + public function getCache(): AdapterInterface; /** * Get first row in the resultset * - * @return bool|\Phalcon\Mvc\ModelInterface + * @return null|\Phalcon\Mvc\ModelInterface */ - public function getFirst(); + public function getFirst(): ?ModelInterface; + + /** + * Returns the current hydration mode + * + * @return int + */ + public function getHydrateMode(): int; /** * Get last row in the resultset * - * @return bool|\Phalcon\Mvc\ModelInterface + * @return null|\Phalcon\Mvc\ModelInterface */ - public function getLast(); + public function getLast(): ?ModelInterface; /** - * Set if the resultset is fresh or an old one cached + * Returns the error messages produced by a batch operation * - * @param bool $isFresh + * @return array|\Phalcon\Messages\MessageInterface[] + */ + public function getMessages(): array; + + /** + * Returns the internal type of data retrieval that the resultset is using + * + * @return int */ - public function setIsFresh($isFresh); + public function getType(): int; /** * Tell if the resultset if fresh or an old one cached * * @return bool */ - public function isFresh(); + public function isFresh(): bool; /** - * Returns the associated cache for the resultset + * Sets the hydration mode in the resultset * - * @return \Phalcon\Cache\BackendInterface + * @param int $hydrateMode + * @return ResultsetInterface */ - public function getCache(); + public function setHydrateMode(int $hydrateMode): ResultsetInterface; + + /** + * Set if the resultset is fresh or an old one cached + * + * @param bool $isFresh + * @return ResultsetInterface + */ + public function setIsFresh(bool $isFresh): ResultsetInterface; /** * Returns a complete resultset as an array, if the resultset has a big number of rows @@ -58,6 +107,15 @@ public function getCache(); * * @return array */ - public function toArray(); + public function toArray(): array; + + /** + * Updates every record in the resultset + * + * @param array $data + * @param \Closure $conditionCallback + * @return bool + */ + public function update($data, \Closure $conditionCallback = null): bool; } diff --git a/src/Phalcon/mvc/model/Row.php b/src/Phalcon/mvc/model/Row.php index 4d910b69..9d9200e2 100644 --- a/src/Phalcon/mvc/model/Row.php +++ b/src/Phalcon/mvc/model/Row.php @@ -12,28 +12,29 @@ class Row implements \Phalcon\Mvc\EntityInterface, \Phalcon\Mvc\Model\ResultInte { /** - * Set the current object's state + * Serializes the object for json_encode * - * @param int $dirtyState - * @return bool + * @return array */ - public function setDirtyState($dirtyState) {} + public function jsonSerialize(): array {} /** - * Checks whether offset exists in the row + * Gets a record in a specific position of the row * - * @param string|int $index - * @return bool + * @param string|int index + * + * @param mixed $index + * @return mixed */ - public function offsetExists($index) {} + public function offsetGet($index) {} /** - * Gets a record in a specific position of the row + * Checks whether offset exists in the row * * @param string|int $index - * @return string|Phalcon\Mvc\ModelInterface + * @return bool */ - public function offsetGet($index) {} + public function offsetExists($index): bool {} /** * Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface @@ -53,39 +54,40 @@ public function offsetUnset($offset) {} /** * Reads an attribute value by its name * - * + * ```php * echo $robot->readAttribute("name"); - * + * ``` * * @param string $attribute * @return mixed */ - public function readAttribute($attribute) {} + public function readAttribute(string $attribute) {} /** - * Writes an attribute value by its name - * - * - * $robot->writeAttribute("name", "Rosey"); - * + * Set the current object's state * - * @param string $attribute - * @param mixed $value + * @param int $dirtyState + * @return bool|\Phalcon\Mvc\ModelInterface */ - public function writeAttribute($attribute, $value) {} + public function setDirtyState(int $dirtyState) {} /** * Returns the instance as an array representation * * @return array */ - public function toArray() {} + public function toArray(): array {} /** - * Serializes the object for json_encode + * Writes an attribute value by its name * - * @return array + * ```php + * $robot->writeAttribute("name", "Rosey"); + * ``` + * + * @param string $attribute + * @param mixed $value */ - public function jsonSerialize() {} + public function writeAttribute(string $attribute, $value) {} } diff --git a/src/Phalcon/mvc/model/Transaction.php b/src/Phalcon/mvc/model/Transaction.php index 072d0f35..6559b68e 100644 --- a/src/Phalcon/mvc/model/Transaction.php +++ b/src/Phalcon/mvc/model/Transaction.php @@ -5,11 +5,12 @@ /** * Phalcon\Mvc\Model\Transaction * - * Transactions are protective blocks where SQL statements are only permanent if they can - * all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. - * Phalcon Transactions should be created using Phalcon\Transaction\Manager. + * Transactions are protective blocks where SQL statements are only permanent if + * they can all succeed as one atomic action. Phalcon\Transaction is intended to + * be used with Phalcon_Model_Base. Phalcon Transactions should be created using + * Phalcon\Transaction\Manager. * - * + * ```php * use Phalcon\Mvc\Model\Transaction\Failed; * use Phalcon\Mvc\Model\Transaction\Manager; * @@ -43,112 +44,108 @@ * } catch(Failed $e) { * echo "Failed, reason: ", $e->getMessage(); * } - * + * ``` */ class Transaction implements \Phalcon\Mvc\Model\TransactionInterface { - protected $_connection; + protected $activeTransaction = false; - protected $_activeTransaction = false; + protected $connection; - protected $_isNewTransaction = true; + protected $isNewTransaction = true; - protected $_rollbackOnAbort = false; + protected $manager; - protected $_manager; + protected $messages; - protected $_messages; + protected $rollbackRecord; - protected $_rollbackRecord; + protected $rollbackOnAbort = false; + + + protected $rollbackThrowException = false; /** * Phalcon\Mvc\Model\Transaction constructor * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @param bool $autoBegin * @param string $service */ - public function __construct(\Phalcon\DiInterface $dependencyInjector, $autoBegin = false, $service = null) {} - - /** - * Sets transaction manager related to the transaction - * - * @param \Phalcon\Mvc\Model\Transaction\ManagerInterface $manager - */ - public function setTransactionManager(\Phalcon\Mvc\Model\Transaction\ManagerInterface $manager) {} + public function __construct(\Phalcon\Di\DiInterface $container, bool $autoBegin = false, string $service = 'db') {} /** * Starts the transaction * * @return bool */ - public function begin() {} + public function begin(): bool {} /** * Commits the transaction * * @return bool */ - public function commit() {} + public function commit(): bool {} /** - * Rollbacks the transaction + * Returns the connection related to transaction * - * @param mixed $rollbackMessage - * @param \Phalcon\Mvc\ModelInterface $rollbackRecord - * @return bool + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function rollback($rollbackMessage = null, \Phalcon\Mvc\ModelInterface $rollbackRecord = null) {} + public function getConnection(): \Phalcon\Db\Adapter\AdapterInterface {} /** - * Returns the connection related to transaction + * Returns validations messages from last save try * - * @return \Phalcon\Db\AdapterInterface + * @return array */ - public function getConnection() {} + public function getMessages(): array {} /** - * Sets if is a reused transaction or new once + * Checks whether transaction is managed by a transaction manager * - * @param bool $isNew + * @return bool */ - public function setIsNewTransaction($isNew) {} + public function isManaged(): bool {} /** - * Sets flag to rollback on abort the HTTP connection + * Checks whether internal connection is under an active transaction * - * @param bool $rollbackOnAbort + * @return bool */ - public function setRollbackOnAbort($rollbackOnAbort) {} + public function isValid(): bool {} /** - * Checks whether transaction is managed by a transaction manager + * Rollbacks the transaction * + * @param string $rollbackMessage + * @param \Phalcon\Mvc\ModelInterface $rollbackRecord * @return bool */ - public function isManaged() {} + public function rollback(string $rollbackMessage = null, \Phalcon\Mvc\ModelInterface $rollbackRecord = null): bool {} /** - * Returns validations messages from last save try + * Sets if is a reused transaction or new once * - * @return array + * @param bool $isNew */ - public function getMessages() {} + public function setIsNewTransaction(bool $isNew) {} /** - * Checks whether internal connection is under an active transaction + * Sets flag to rollback on abort the HTTP connection * - * @return bool + * @param bool $rollbackOnAbort */ - public function isValid() {} + public function setRollbackOnAbort(bool $rollbackOnAbort) {} /** * Sets object which generates rollback action @@ -157,4 +154,19 @@ public function isValid() {} */ public function setRollbackedRecord(\Phalcon\Mvc\ModelInterface $record) {} + /** + * Sets transaction manager related to the transaction + * + * @param \Phalcon\Mvc\Model\Transaction\ManagerInterface $manager + */ + public function setTransactionManager(\Phalcon\Mvc\Model\Transaction\ManagerInterface $manager) {} + + /** + * Enables throwing exception + * + * @param bool $status + * @return \Phalcon\Mvc\Model\TransactionInterface + */ + public function throwRollbackException(bool $status): TransactionInterface {} + } diff --git a/src/Phalcon/mvc/model/TransactionInterface.php b/src/Phalcon/mvc/model/TransactionInterface.php index d1715dee..da437029 100644 --- a/src/Phalcon/mvc/model/TransactionInterface.php +++ b/src/Phalcon/mvc/model/TransactionInterface.php @@ -10,76 +10,70 @@ interface TransactionInterface { - /** - * Sets transaction manager related to the transaction - * - * @param \Phalcon\Mvc\Model\Transaction\ManagerInterface $manager - */ - public function setTransactionManager(\Phalcon\Mvc\Model\Transaction\ManagerInterface $manager); - /** * Starts the transaction * * @return bool */ - public function begin(); + public function begin(): bool; /** * Commits the transaction * * @return bool */ - public function commit(); + public function commit(): bool; /** - * Rollbacks the transaction + * Returns connection related to transaction * - * @param mixed $rollbackMessage - * @param \Phalcon\Mvc\ModelInterface $rollbackRecord + * @return \Phalcon\Db\Adapter\AdapterInterface */ - public function rollback($rollbackMessage = null, \Phalcon\Mvc\ModelInterface $rollbackRecord = null); + public function getConnection(): \Phalcon\Db\Adapter\AdapterInterface; /** - * Returns connection related to transaction + * Returns validations messages from last save try * - * @return \Phalcon\Db\AdapterInterface + * @return array */ - public function getConnection(); + public function getMessages(): array; /** - * Sets if is a reused transaction or new once + * Checks whether transaction is managed by a transaction manager * - * @param bool $isNew + * @return bool */ - public function setIsNewTransaction($isNew); + public function isManaged(): bool; /** - * Sets flag to rollback on abort the HTTP connection + * Checks whether internal connection is under an active transaction * - * @param bool $rollbackOnAbort + * @return bool */ - public function setRollbackOnAbort($rollbackOnAbort); + public function isValid(): bool; /** - * Checks whether transaction is managed by a transaction manager + * Rollbacks the transaction * + * @param string $rollbackMessage + * @param \Phalcon\Mvc\ModelInterface $rollbackRecord * @return bool */ - public function isManaged(); + public function rollback(string $rollbackMessage = null, \Phalcon\Mvc\ModelInterface $rollbackRecord = null): bool; /** - * Returns validations messages from last save try + * Sets if is a reused transaction or new once * - * @return array + * @param bool $isNew */ - public function getMessages(); + public function setIsNewTransaction(bool $isNew); /** - * Checks whether internal connection is under an active transaction + * Sets flag to rollback on abort the HTTP connection * - * @return bool + * @param bool $rollbackOnAbort */ - public function isValid(); + public function setRollbackOnAbort(bool $rollbackOnAbort); /** * Sets object which generates rollback action @@ -88,4 +82,19 @@ public function isValid(); */ public function setRollbackedRecord(\Phalcon\Mvc\ModelInterface $record); + /** + * Sets transaction manager related to the transaction + * + * @param \Phalcon\Mvc\Model\Transaction\ManagerInterface $manager + */ + public function setTransactionManager(\Phalcon\Mvc\Model\Transaction\ManagerInterface $manager); + + /** + * Enables throwing exception + * + * @param bool $status + * @return TransactionInterface + */ + public function throwRollbackException(bool $status): TransactionInterface; + } diff --git a/src/Phalcon/mvc/model/ValidationFailed.php b/src/Phalcon/mvc/model/ValidationFailed.php index f491a341..e64943b7 100644 --- a/src/Phalcon/mvc/model/ValidationFailed.php +++ b/src/Phalcon/mvc/model/ValidationFailed.php @@ -11,32 +11,32 @@ class ValidationFailed extends \Phalcon\Mvc\Model\Exception { - protected $_model; + protected $messages; - protected $_messages; + protected $model; /** * Phalcon\Mvc\Model\ValidationFailed constructor * - * @param Model $model + * @param \Phalcon\Mvc\ModelInterface $model * @param Message[] $validationMessages */ - public function __construct(\Phalcon\Mvc\Model $model, array $validationMessages) {} + public function __construct(\Phalcon\Mvc\ModelInterface $model, array $validationMessages) {} /** - * Returns the model that generated the messages + * Returns the complete group of messages produced in the validation * - * @return \Phalcon\Mvc\Model + * @return array|Message[] */ - public function getModel() {} + public function getMessages(): array {} /** - * Returns the complete group of messages produced in the validation + * Returns the model that generated the messages * - * @return Message[] + * @return \Phalcon\Mvc\ModelInterface */ - public function getMessages() {} + public function getModel(): ModelInterface {} } diff --git a/src/Phalcon/mvc/model/Validator.php b/src/Phalcon/mvc/model/Validator.php deleted file mode 100644 index a5b17579..00000000 --- a/src/Phalcon/mvc/model/Validator.php +++ /dev/null @@ -1,73 +0,0 @@ - - * $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( - * [ - * "prefix" => "my-app-id", - * "lifetime" => 86400, - * ] - * ); - * - * - * @deprecated Deprecated since 3.3.0, will be removed in 4.0.0 - * @see Phalcon\Mvc\Model\Metadata\Apcu - */ -class Apc extends \Phalcon\Mvc\Model\MetaData -{ - - protected $_prefix = ''; - - - protected $_ttl = 172800; - - - protected $_metaData = array(); - - - /** - * Phalcon\Mvc\Model\MetaData\Apc constructor - * - * @param array $options - */ - public function __construct($options = null) {} - - /** - * Reads meta-data from APC - * - * @param string $key - * @return array|null - */ - public function read($key) {} - - /** - * Writes the meta-data to APC - * - * @param string $key - * @param mixed $data - */ - public function write($key, $data) {} - -} diff --git a/src/Phalcon/mvc/model/metadata/Apcu.php b/src/Phalcon/mvc/model/metadata/Apcu.php index d27a7af2..b676700d 100644 --- a/src/Phalcon/mvc/model/metadata/Apcu.php +++ b/src/Phalcon/mvc/model/metadata/Apcu.php @@ -11,48 +11,24 @@ * * You can query the meta-data by printing apcu_fetch('$PMM$') or apcu_fetch('$PMM$my-app-id') * - * - * $metaData = new \Phalcon\Mvc\Model\Metadata\Apcu( + * ```php + * $metaData = new \Phalcon\Mvc\Model\MetaData\Apcu( * [ * "prefix" => "my-app-id", * "lifetime" => 86400, * ] * ); - * + * ``` */ class Apcu extends \Phalcon\Mvc\Model\MetaData { - protected $_prefix = ''; - - - protected $_ttl = 172800; - - - protected $_metaData = array(); - - /** * Phalcon\Mvc\Model\MetaData\Apcu constructor * + * @param \Phalcon\Cache\AdapterFactory $factory * @param array $options */ - public function __construct($options = null) {} - - /** - * Reads meta-data from APCu - * - * @param string $key - * @return array|null - */ - public function read($key) {} - - /** - * Writes the meta-data to APCu - * - * @param string $key - * @param mixed $data - */ - public function write($key, $data) {} + public function __construct(\Phalcon\Cache\AdapterFactory $factory, array $options = null) {} } diff --git a/src/Phalcon/mvc/model/metadata/Libmemcached.php b/src/Phalcon/mvc/model/metadata/Libmemcached.php index ef4640b7..fad94fe0 100644 --- a/src/Phalcon/mvc/model/metadata/Libmemcached.php +++ b/src/Phalcon/mvc/model/metadata/Libmemcached.php @@ -8,61 +8,17 @@ * Stores model meta-data in the Memcache. * * By default meta-data is stored for 48 hours (172800 seconds) - * - * - * $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( - * [ - * "servers" => [ - * [ - * "host" => "localhost", - * "port" => 11211, - * "weight" => 1, - * ], - * ], - * "client" => [ - * Memcached::OPT_HASH => Memcached::HASH_MD5, - * Memcached::OPT_PREFIX_KEY => "prefix.", - * ], - * "lifetime" => 3600, - * "prefix" => "my_", - * ] - * ); - * */ class Libmemcached extends \Phalcon\Mvc\Model\MetaData { - protected $_ttl = 172800; - - - protected $_memcache = null; - - - protected $_metaData = array(); - - /** * Phalcon\Mvc\Model\MetaData\Libmemcached constructor * + * @param \Phalcon\Cache\AdapterFactory $factory * @param array $options */ - public function __construct($options = null) {} - - /** - * Reads metadata from Memcache - * - * @param string $key - * @return array|null - */ - public function read($key) {} - - /** - * Writes the metadata to Memcache - * - * @param string $key - * @param mixed $data - */ - public function write($key, $data) {} + public function __construct(\Phalcon\Cache\AdapterFactory $factory, array $options = array()) {} /** * Flush Memcache data and resets internal meta-data in order to regenerate it diff --git a/src/Phalcon/mvc/model/metadata/Memcache.php b/src/Phalcon/mvc/model/metadata/Memcache.php deleted file mode 100644 index b846ab98..00000000 --- a/src/Phalcon/mvc/model/metadata/Memcache.php +++ /dev/null @@ -1,64 +0,0 @@ - - * $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( - * [ - * "prefix" => "my-app-id", - * "lifetime" => 86400, - * "host" => "localhost", - * "port" => 11211, - * "persistent" => false, - * ] - * ); - * - */ -class Memcache extends \Phalcon\Mvc\Model\MetaData -{ - - protected $_ttl = 172800; - - - protected $_memcache = null; - - - protected $_metaData = array(); - - - /** - * Phalcon\Mvc\Model\MetaData\Memcache constructor - * - * @param array $options - */ - public function __construct($options = null) {} - - /** - * Reads metadata from Memcache - * - * @param string $key - * @return array|null - */ - public function read($key) {} - - /** - * Writes the metadata to Memcache - * - * @param string $key - * @param mixed $data - */ - public function write($key, $data) {} - - /** - * Flush Memcache data and resets internal meta-data in order to regenerate it - */ - public function reset() {} - -} diff --git a/src/Phalcon/mvc/model/metadata/Memory.php b/src/Phalcon/mvc/model/metadata/Memory.php index 57966816..c647040f 100644 --- a/src/Phalcon/mvc/model/metadata/Memory.php +++ b/src/Phalcon/mvc/model/metadata/Memory.php @@ -10,9 +10,6 @@ class Memory extends \Phalcon\Mvc\Model\MetaData { - protected $_metaData = array(); - - /** * Phalcon\Mvc\Model\MetaData\Memory constructor * @@ -24,9 +21,9 @@ public function __construct($options = null) {} * Reads the meta-data from temporal memory * * @param string $key - * @return array + * @return array|null */ - public function read($key) {} + public function read(string $key): ?array {} /** * Writes the meta-data to temporal memory @@ -34,6 +31,6 @@ public function read($key) {} * @param string $key * @param array $data */ - public function write($key, $data) {} + public function write(string $key, array $data) {} } diff --git a/src/Phalcon/mvc/model/metadata/Redis.php b/src/Phalcon/mvc/model/metadata/Redis.php index 6b357aec..c32c0bca 100644 --- a/src/Phalcon/mvc/model/metadata/Redis.php +++ b/src/Phalcon/mvc/model/metadata/Redis.php @@ -9,55 +9,30 @@ * * By default meta-data is stored for 48 hours (172800 seconds) * - * - * use Phalcon\Mvc\Model\Metadata\Redis; + * ```php + * use Phalcon\Mvc\Model\MetaData\Redis; * * $metaData = new Redis( * [ * "host" => "127.0.0.1", * "port" => 6379, * "persistent" => 0, - * "statsKey" => "_PHCM_MM", * "lifetime" => 172800, * "index" => 2, * ] * ); - * + * ``` */ class Redis extends \Phalcon\Mvc\Model\MetaData { - protected $_ttl = 172800; - - - protected $_redis = null; - - - protected $_metaData = array(); - - /** * Phalcon\Mvc\Model\MetaData\Redis constructor * + * @param \Phalcon\Cache\AdapterFactory $factory * @param array $options */ - public function __construct($options = null) {} - - /** - * Reads metadata from Redis - * - * @param string $key - * @return array|null - */ - public function read($key) {} - - /** - * Writes the metadata to Redis - * - * @param string $key - * @param mixed $data - */ - public function write($key, $data) {} + public function __construct(\Phalcon\Cache\AdapterFactory $factory, array $options = array()) {} /** * Flush Redis data and resets internal meta-data in order to regenerate it diff --git a/src/Phalcon/mvc/model/metadata/Session.php b/src/Phalcon/mvc/model/metadata/Session.php deleted file mode 100644 index 048388de..00000000 --- a/src/Phalcon/mvc/model/metadata/Session.php +++ /dev/null @@ -1,50 +0,0 @@ - - * $metaData = new \Phalcon\Mvc\Model\Metadata\Session( - * [ - * "prefix" => "my-app-id", - * ] - * ); - * - */ -class Session extends \Phalcon\Mvc\Model\MetaData -{ - - protected $_prefix = ''; - - - /** - * Phalcon\Mvc\Model\MetaData\Session constructor - * - * @param array $options - */ - public function __construct($options = null) {} - - /** - * Reads meta-data from $_SESSION - * - * @param string $key - * @return array - */ - public function read($key) {} - - /** - * Writes the meta-data to $_SESSION - * - * @param string $key - * @param array $data - */ - public function write($key, $data) {} - -} diff --git a/src/Phalcon/mvc/model/metadata/StrategyInterface.php b/src/Phalcon/mvc/model/metadata/StrategyInterface.php index 82b2a4d6..9ba73ec4 100644 --- a/src/Phalcon/mvc/model/metadata/StrategyInterface.php +++ b/src/Phalcon/mvc/model/metadata/StrategyInterface.php @@ -2,27 +2,34 @@ namespace Phalcon\Mvc\Model\MetaData; - +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ interface StrategyInterface { /** - * The meta-data is obtained by reading the column descriptions from the database information schema + * Read the model's column map, this can't be inferred * + * @todo Not implemented * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector); + public function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array; /** - * Read the model's column map, this can't be inferred + * The meta-data is obtained by reading the column descriptions from the database information schema * - * @todo Not implemented * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector); + public function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array; } diff --git a/src/Phalcon/mvc/model/metadata/Files.php b/src/Phalcon/mvc/model/metadata/Stream.php similarity index 57% rename from src/Phalcon/mvc/model/metadata/Files.php rename to src/Phalcon/mvc/model/metadata/Stream.php index 419c3016..c14155d6 100644 --- a/src/Phalcon/mvc/model/metadata/Files.php +++ b/src/Phalcon/mvc/model/metadata/Stream.php @@ -3,25 +3,22 @@ namespace Phalcon\Mvc\Model\MetaData; /** - * Phalcon\Mvc\Model\MetaData\Files + * Phalcon\Mvc\Model\MetaData\Stream * * Stores model meta-data in PHP files. * - * + * ```php * $metaData = new \Phalcon\Mvc\Model\MetaData\Files( * [ * "metaDataDir" => "app/cache/metadata/", * ] * ); - * + * ``` */ -class Files extends \Phalcon\Mvc\Model\MetaData +class Stream extends \Phalcon\Mvc\Model\MetaData { - protected $_metaDataDir = './'; - - - protected $_metaData = array(); + protected $metaDataDir = './'; /** @@ -35,9 +32,9 @@ public function __construct($options = null) {} * Reads meta-data from files * * @param string $key - * @return mixed + * @return array|null */ - public function read($key) {} + public function read(string $key): ?array {} /** * Writes the meta-data to files @@ -45,6 +42,13 @@ public function read($key) {} * @param string $key * @param array $data */ - public function write($key, $data) {} + public function write(string $key, array $data) {} + + /** + * Throws an exception when the metadata cannot be written + * + * @param mixed $option + */ + private function throwWriteException($option) {} } diff --git a/src/Phalcon/mvc/model/metadata/Xcache.php b/src/Phalcon/mvc/model/metadata/Xcache.php deleted file mode 100644 index bffa8d74..00000000 --- a/src/Phalcon/mvc/model/metadata/Xcache.php +++ /dev/null @@ -1,58 +0,0 @@ - - * $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( - * [ - * "prefix" => "my-app-id", - * "lifetime" => 86400, - * ] - * ); - * - */ -class Xcache extends \Phalcon\Mvc\Model\MetaData -{ - - protected $_prefix = ''; - - - protected $_ttl = 172800; - - - protected $_metaData = array(); - - - /** - * Phalcon\Mvc\Model\MetaData\Xcache constructor - * - * @param array $options - */ - public function __construct($options = null) {} - - /** - * Reads metadata from XCache - * - * @param string $key - * @return array - */ - public function read($key) {} - - /** - * Writes the metadata to XCache - * - * @param string $key - * @param array $data - */ - public function write($key, $data) {} - -} diff --git a/src/Phalcon/mvc/model/metadata/strategy/Annotations.php b/src/Phalcon/mvc/model/metadata/strategy/Annotations.php index af7790fa..86f0806f 100644 --- a/src/Phalcon/mvc/model/metadata/strategy/Annotations.php +++ b/src/Phalcon/mvc/model/metadata/strategy/Annotations.php @@ -2,26 +2,33 @@ namespace Phalcon\Mvc\Model\MetaData\Strategy; - +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ class Annotations implements \Phalcon\Mvc\Model\MetaData\StrategyInterface { /** - * The meta-data is obtained by reading the column descriptions from the database information schema + * Read the model's column map, this can't be inferred * * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public final function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector) {} + final public function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array {} /** - * Read the model's column map, this can't be inferred + * The meta-data is obtained by reading the column descriptions from the database information schema * * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public final function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector) {} + final public function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array {} } diff --git a/src/Phalcon/mvc/model/metadata/strategy/Introspection.php b/src/Phalcon/mvc/model/metadata/strategy/Introspection.php index 3f61fd1a..361aa28e 100644 --- a/src/Phalcon/mvc/model/metadata/strategy/Introspection.php +++ b/src/Phalcon/mvc/model/metadata/strategy/Introspection.php @@ -11,21 +11,21 @@ class Introspection implements \Phalcon\Mvc\Model\MetaData\StrategyInterface { /** - * The meta-data is obtained by reading the column descriptions from the database information schema + * Read the model's column map, this can't be inferred * * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public final function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector) {} + final public function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array {} /** - * Read the model's column map, this can't be inferred + * The meta-data is obtained by reading the column descriptions from the database information schema * * @param \Phalcon\Mvc\ModelInterface $model - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container * @return array */ - public final function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector) {} + final public function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\Di\DiInterface $container): array {} } diff --git a/src/Phalcon/mvc/model/query/Builder.php b/src/Phalcon/mvc/model/query/Builder.php index df6ecfc3..73447ad5 100644 --- a/src/Phalcon/mvc/model/query/Builder.php +++ b/src/Phalcon/mvc/model/query/Builder.php @@ -7,9 +7,11 @@ * * Helps to create PHQL queries using an OO interface * - * + * ```php * $params = [ - * "models" => ["Users"], + * "models" => [ + * Users::class, + * ], * "columns" => ["id", "name", "status"], * "conditions" => [ * [ @@ -34,111 +36,176 @@ * ]; * * $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); - * + * ``` */ class Builder implements \Phalcon\Mvc\Model\Query\BuilderInterface, \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; - + protected $bindParams; - protected $_columns; + protected $bindTypes; - protected $_models; + protected $columns; - protected $_joins; - - /** - * @deprecated Will be removed in version 4.0.0 - */ - protected $_with; + protected $conditions; - protected $_conditions; + protected $container; - protected $_group; + protected $distinct; - protected $_having; + protected $forUpdate; - protected $_order; + /** + * @var array + */ + protected $group; - protected $_limit; + protected $having; - protected $_offset; + protected $hiddenParamNumber = 0; - protected $_forUpdate; + protected $joins; - protected $_sharedLock; + protected $limit; - protected $_bindParams; + protected $models; - protected $_bindTypes; + protected $offset; - protected $_distinct; + protected $order; - protected $_hiddenParamNumber = 0; + protected $sharedLock; /** * Phalcon\Mvc\Model\Query\Builder constructor * * @param mixed $params - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function __construct($params = null, \Phalcon\DiInterface $dependencyInjector = null) {} + public function __construct($params = null, \Phalcon\Di\DiInterface $container = null) {} /** - * Sets the DependencyInjector container + * Add a model to take part of the query + * + * ```php + * // Load data from models Robots + * $builder->addFrom( + * Robots::class + * ); * - * @param \Phalcon\DiInterface $dependencyInjector - * @return Builder + * // Load data from model 'Robots' using 'r' as alias in PHQL + * $builder->addFrom( + * Robots::class, + * "r" + * ); + * ``` + * + * @param string $model + * @param string $alias + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function addFrom(string $model, string $alias = null): BuilderInterface {} /** - * Returns the DependencyInjector container + * Appends a condition to the current HAVING conditions clause using a AND operator * - * @return \Phalcon\DiInterface + * ```php + * $builder->andHaving("SUM(Robots.price) > 0"); + * + * $builder->andHaving( + * "SUM(Robots.price) > :sum:", + * [ + * "sum" => 100, + * ] + * ); + * ``` + * + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getDI() {} + public function andHaving(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** - * Sets SELECT DISTINCT / SELECT ALL flag + * Appends a condition to the current WHERE conditions using a AND operator * - * - * $builder->distinct("status"); - * $builder->distinct(null); - * + * ```php + * $builder->andWhere("name = 'Peter'"); * - * @param mixed $distinct - * @return Builder + * $builder->andWhere( + * "name = :name: AND id > :id:", + * [ + * "name" => "Peter", + * "id" => 100, + * ] + * ); + * ``` + * + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function distinct($distinct) {} + public function andWhere(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** - * Returns SELECT DISTINCT / SELECT ALL flag + * Automatically escapes identifiers but only if they need to be escaped. * - * @return bool + * @param string $identifier + * @return string + */ + final public function autoescape(string $identifier): string {} + + /** + * Appends a BETWEEN condition to the current HAVING conditions clause + * + * ```php + * $builder->betweenHaving("SUM(Robots.price)", 100.25, 200.50); + * ``` + * + * @param string $expr + * @param mixed $minimum + * @param mixed $maximum + * @param string $operator + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getDistinct() {} + public function betweenHaving(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} + + /** + * Appends a BETWEEN condition to the current WHERE conditions + * + * ```php + * $builder->betweenWhere("price", 100.25, 200.50); + * ``` + * + * @param string $expr + * @param mixed $minimum + * @param mixed $maximum + * @param string $operator + * @return \Phalcon\Mvc\Model\Query\BuilderInterface + */ + public function betweenWhere(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** * Sets the columns to be queried * - * + * ```php * $builder->columns("id, name"); * * $builder->columns( @@ -154,65 +221,100 @@ public function getDistinct() {} * "number" => "COUNT()", * ] * ); - * + * ``` * * @param mixed $columns - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function columns($columns) {} + public function columns($columns): BuilderInterface {} /** - * Return the columns to be queried + * Sets SELECT DISTINCT / SELECT ALL flag * - * @return string|array + * ```php + * $builder->distinct("status"); + * $builder->distinct(null); + * ``` + * + * @param mixed $distinct + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getColumns() {} + public function distinct($distinct): BuilderInterface {} + + /** + * Sets a FOR UPDATE clause + * + * ```php + * $builder->forUpdate(true); + * ``` + * + * @param bool $forUpdate + * @return \Phalcon\Mvc\Model\Query\BuilderInterface + */ + public function forUpdate(bool $forUpdate): BuilderInterface {} /** * Sets the models who makes part of the query * - * - * $builder->from("Robots"); + * ```php + * $builder->from( + * Robots::class + * ); * * $builder->from( * [ - * "Robots", - * "RobotsParts", + * Robots::class, + * RobotsParts::class, * ] * ); * * $builder->from( * [ - * "r" => "Robots", - * "rp" => "RobotsParts", + * "r" => Robots::class, + * "rp" => RobotsParts::class, * ] * ); - * + * ``` * * @param mixed $models - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function from($models) {} + public function from($models): BuilderInterface {} /** - * Add a model to take part of the query + * Returns default bind params * - * NOTE: The third parameter $with is deprecated and will be removed in future releases. + * @return array + */ + public function getBindParams(): array {} + + /** + * Returns default bind types * - * - * // Load data from models Robots - * $builder->addFrom("Robots"); + * @return array + */ + public function getBindTypes(): array {} + + /** + * Return the columns to be queried * - * // Load data from model 'Robots' using 'r' as alias in PHQL - * $builder->addFrom("Robots", "r"); - * + * @return string|array + */ + public function getColumns() {} + + /** + * Returns the DependencyInjector container * - * @param mixed $model - * @param mixed $alias - * @param mixed $with - * @return Builder + * @return \Phalcon\Di\DiInterface */ - public function addFrom($model, $alias = null, $with = null) {} + public function getDI(): DiInterface {} + + /** + * Returns SELECT DISTINCT / SELECT ALL flag + * + * @return bool + */ + public function getDistinct(): bool {} /** * Return the models who makes part of the query @@ -222,466 +324,439 @@ public function addFrom($model, $alias = null, $with = null) {} public function getFrom() {} /** - * Adds an :type: join (by default type - INNER) to the query - * - * - * // Inner Join model 'Robots' with automatic conditions and alias - * $builder->join("Robots"); - * - * // Inner Join model 'Robots' specifying conditions - * $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); - * - * // Inner Join model 'Robots' specifying conditions and alias - * $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); - * - * // Left Join model 'Robots' specifying conditions, alias and type of join - * $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); - * + * Returns the GROUP BY clause * - * @param string $model - * @param string $conditions - * @param string $alias - * @param string $type - * @return Builder + * @return array */ - public function join($model, $conditions = null, $alias = null, $type = null) {} + public function getGroupBy(): array {} /** - * Adds an INNER join to the query - * - * - * // Inner Join model 'Robots' with automatic conditions and alias - * $builder->innerJoin("Robots"); - * - * // Inner Join model 'Robots' specifying conditions - * $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); - * - * // Inner Join model 'Robots' specifying conditions and alias - * $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * Return the current having clause * - * @param string $model - * @param string $conditions - * @param string $alias - * @param string $type - * @return Builder + * @return string */ - public function innerJoin($model, $conditions = null, $alias = null) {} + public function getHaving(): string {} /** - * Adds a LEFT join to the query - * - * - * $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * Return join parts of the query * - * @param string $model - * @param string $conditions - * @param string $alias - * @return Builder + * @return array */ - public function leftJoin($model, $conditions = null, $alias = null) {} + public function getJoins(): array {} /** - * Adds a RIGHT join to the query - * - * - * $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); - * + * Returns the current LIMIT clause * - * @param string $model - * @param string $conditions - * @param string $alias - * @return Builder + * @return string|array */ - public function rightJoin($model, $conditions = null, $alias = null) {} + public function getLimit() {} /** - * Return join parts of the query + * Returns the models involved in the query * - * @return array + * @return string|array|null */ - public function getJoins() {} + public function getModels() {} /** - * Sets the query WHERE conditions + * Returns the current OFFSET clause * - * - * $builder->where(100); + * @return int + */ + public function getOffset(): int {} + + /** + * Returns the set ORDER BY clause * - * $builder->where("name = 'Peter'"); + * @return string|array + */ + public function getOrderBy() {} + + /** + * Returns a PHQL statement built based on the builder parameters * - * $builder->where( - * "name = :name: AND id > :id:", - * [ - * "name" => "Peter", - * "id" => 100, - * ] - * ); - * + * @return string + */ + final public function getPhql(): string {} + + /** + * Returns the query built * - * @param mixed $conditions - * @param array $bindParams - * @param array $bindTypes - * @return Builder + * @return \Phalcon\Mvc\Model\QueryInterface */ - public function where($conditions, $bindParams = null, $bindTypes = null) {} + public function getQuery(): QueryInterface {} /** - * Appends a condition to the current WHERE conditions using a AND operator + * Return the conditions for the query * - * - * $builder->andWhere("name = 'Peter'"); + * @return string|array + */ + public function getWhere() {} + + /** + * Sets a GROUP BY clause * - * $builder->andWhere( - * "name = :name: AND id > :id:", + * ```php + * $builder->groupBy( * [ - * "name" => "Peter", - * "id" => 100, + * "Robots.name", * ] * ); - * + * ``` * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return Builder + * @param string|array $group + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function andWhere($conditions, $bindParams = null, $bindTypes = null) {} + public function groupBy($group): BuilderInterface {} /** - * Appends a condition to the current conditions using an OR operator + * Sets the HAVING condition clause * - * - * $builder->orWhere("name = 'Peter'"); + * ```php + * $builder->having("SUM(Robots.price) > 0"); * - * $builder->orWhere( - * "name = :name: AND id > :id:", + * $builder->having( + * "SUM(Robots.price) > :sum:", * [ - * "name" => "Peter", - * "id" => 100, + * "sum" => 100, * ] * ); - * + * ``` * - * @param string $conditions + * @param mixed $conditions * @param array $bindParams * @param array $bindTypes - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function orWhere($conditions, $bindParams = null, $bindTypes = null) {} + public function having($conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** - * Appends a BETWEEN condition to the current WHERE conditions + * Appends an IN condition to the current HAVING conditions clause * - * - * $builder->betweenWhere("price", 100.25, 200.50); - * + * ```php + * $builder->inHaving("SUM(Robots.price)", [100, 200]); + * ``` * * @param string $expr - * @param mixed $minimum - * @param mixed $maximum + * @param array $values * @param string $operator - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function betweenWhere($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND) {} + public function inHaving(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Appends a NOT BETWEEN condition to the current WHERE conditions + * Adds an INNER join to the query * - * - * $builder->notBetweenWhere("price", 100.25, 200.50); - * + * ```php + * // Inner Join model 'Robots' with automatic conditions and alias + * $builder->innerJoin( + * Robots::class + * ); * - * @param string $expr - * @param mixed $minimum - * @param mixed $maximum - * @param string $operator - * @return Builder - */ - public function notBetweenWhere($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND) {} - - /** - * Appends an IN condition to the current WHERE conditions + * // Inner Join model 'Robots' specifying conditions + * $builder->innerJoin( + * Robots::class, + * "Robots.id = RobotsParts.robots_id" + * ); * - * - * $builder->inWhere("id", [1, 2, 3]); - * + * // Inner Join model 'Robots' specifying conditions and alias + * $builder->innerJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); + * ``` * - * @param string $expr - * @param array $values - * @param string $operator + * @param string $model + * @param string $conditions + * @param string $alias * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function inWhere($expr, array $values, $operator = BuilderInterface::OPERATOR_AND) {} + public function innerJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface {} /** - * Appends a NOT IN condition to the current WHERE conditions + * Appends an IN condition to the current WHERE conditions * - * - * $builder->notInWhere("id", [1, 2, 3]); - * + * ```php + * $builder->inWhere( + * "id", + * [1, 2, 3] + * ); + * ``` * * @param string $expr * @param array $values * @param string $operator * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function notInWhere($expr, array $values, $operator = BuilderInterface::OPERATOR_AND) {} + public function inWhere(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Return the conditions for the query - * - * @return string|array - */ - public function getWhere() {} - - /** - * Sets an ORDER BY condition clause - * - * - * $builder->orderBy("Robots.name"); - * $builder->orderBy(["1", "Robots.name"]); - * $builder->orderBy(["Robots.name DESC"]); - * + * Adds an :type: join (by default type - INNER) to the query * - * @param string|array $orderBy - * @return Builder - */ - public function orderBy($orderBy) {} - - /** - * Returns the set ORDER BY clause + * ```php + * // Inner Join model 'Robots' with automatic conditions and alias + * $builder->join( + * Robots::class + * ); * - * @return string|array - */ - public function getOrderBy() {} - - /** - * Sets the HAVING condition clause + * // Inner Join model 'Robots' specifying conditions + * $builder->join( + * Robots::class, + * "Robots.id = RobotsParts.robots_id" + * ); * - * - * $builder->having("SUM(Robots.price) > 0"); + * // Inner Join model 'Robots' specifying conditions and alias + * $builder->join( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" + * ); * - * $builder->having( - * "SUM(Robots.price) > :sum:", - * [ - * "sum" => 100, - * ] + * // Left Join model 'Robots' specifying conditions, alias and type of join + * $builder->join( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r", + * "LEFT" * ); - * + * ``` * - * @param mixed $conditions - * @param array $bindParams - * @param array $bindTypes - * @return Builder + * @param string $model + * @param string $conditions + * @param string $alias + * @param string $type + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function having($conditions, $bindParams = null, $bindTypes = null) {} + public function join(string $model, string $conditions = null, string $alias = null, string $type = null): BuilderInterface {} /** - * Appends a condition to the current HAVING conditions clause using a AND operator - * - * - * $builder->andHaving("SUM(Robots.price) > 0"); + * Adds a LEFT join to the query * - * $builder->andHaving( - * "SUM(Robots.price) > :sum:", - * [ - * "sum" => 100, - * ] + * ```php + * $builder->leftJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" * ); - * + * ``` * + * @param string $model * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return Builder + * @param string $alias + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function andHaving($conditions, $bindParams = null, $bindTypes = null) {} + public function leftJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface {} /** - * Appends a condition to the current HAVING conditions clause using an OR operator - * - * - * $builder->orHaving("SUM(Robots.price) > 0"); + * Sets a LIMIT clause, optionally an offset clause * - * $builder->orHaving( - * "SUM(Robots.price) > :sum:", - * [ - * "sum" => 100, - * ] - * ); - * + * ```php + * $builder->limit(100); + * $builder->limit(100, 20); + * $builder->limit("100", "20"); + * ``` * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return Builder + * @param int $limit + * @param mixed $offset + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function orHaving($conditions, $bindParams = null, $bindTypes = null) {} + public function limit(int $limit, $offset = null): BuilderInterface {} /** - * Appends a BETWEEN condition to the current HAVING conditions clause + * Appends a NOT BETWEEN condition to the current HAVING conditions clause * - * - * $builder->betweenHaving("SUM(Robots.price)", 100.25, 200.50); - * + * ```php + * $builder->notBetweenHaving("SUM(Robots.price)", 100.25, 200.50); + * ``` * * @param string $expr * @param mixed $minimum * @param mixed $maximum * @param string $operator - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function betweenHaving($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND) {} + public function notBetweenHaving(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Appends a NOT BETWEEN condition to the current HAVING conditions clause + * Appends a NOT BETWEEN condition to the current WHERE conditions * - * - * $builder->notBetweenHaving("SUM(Robots.price)", 100.25, 200.50); - * + * ```php + * $builder->notBetweenWhere("price", 100.25, 200.50); + * ``` * * @param string $expr * @param mixed $minimum * @param mixed $maximum * @param string $operator - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function notBetweenHaving($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND) {} + public function notBetweenWhere(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Appends an IN condition to the current HAVING conditions clause + * Appends a NOT IN condition to the current HAVING conditions clause * - * - * $builder->inHaving("SUM(Robots.price)", [100, 200]); - * + * ```php + * $builder->notInHaving("SUM(Robots.price)", [100, 200]); + * ``` * * @param string $expr * @param array $values * @param string $operator - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function inHaving($expr, array $values, $operator = BuilderInterface::OPERATOR_AND) {} + public function notInHaving(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Appends a NOT IN condition to the current HAVING conditions clause + * Appends a NOT IN condition to the current WHERE conditions * - * - * $builder->notInHaving("SUM(Robots.price)", [100, 200]); - * + * ```php + * $builder->notInWhere("id", [1, 2, 3]); + * ``` * * @param string $expr * @param array $values * @param string $operator - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function notInHaving($expr, array $values, $operator = BuilderInterface::OPERATOR_AND) {} + public function notInWhere(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface {} /** - * Return the current having clause + * Sets an OFFSET clause * - * @return string + * ```php + * $builder->offset(30); + * ``` + * + * @param int $offset + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getHaving() {} + public function offset(int $offset): BuilderInterface {} /** - * Sets a FOR UPDATE clause + * Sets an ORDER BY condition clause * - * - * $builder->forUpdate(true); - * + * ```php + * $builder->orderBy("Robots.name"); + * $builder->orderBy(["1", "Robots.name"]); + * $builder->orderBy(["Robots.name DESC"]); + * ``` * - * @param bool $forUpdate - * @return Builder + * @param string|array $orderBy + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function forUpdate($forUpdate) {} + public function orderBy($orderBy): BuilderInterface {} /** - * Sets a LIMIT clause, optionally an offset clause + * Appends a condition to the current HAVING conditions clause using an OR operator * - * - * $builder->limit(100); - * $builder->limit(100, 20); - * $builder->limit("100", "20"); - * + * ```php + * $builder->orHaving("SUM(Robots.price) > 0"); * - * @param int $limit - * @param mixed $offset - * @return Builder - */ - public function limit($limit, $offset = null) {} - - /** - * Returns the current LIMIT clause + * $builder->orHaving( + * "SUM(Robots.price) > :sum:", + * [ + * "sum" => 100, + * ] + * ); + * ``` * - * @return string|array + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getLimit() {} + public function orHaving(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** - * Sets an OFFSET clause + * Appends a condition to the current conditions using an OR operator * - * - * $builder->offset(30); - * + * ```php + * $builder->orWhere("name = 'Peter'"); * - * @param int $offset - * @return Builder - */ - public function offset($offset) {} - - /** - * Returns the current OFFSET clause + * $builder->orWhere( + * "name = :name: AND id > :id:", + * [ + * "name" => "Peter", + * "id" => 100, + * ] + * ); + * ``` * - * @return string|array + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getOffset() {} + public function orWhere(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** - * Sets a GROUP BY clause + * Adds a RIGHT join to the query * - * - * $builder->groupBy( - * [ - * "Robots.name", - * ] + * ```php + * $builder->rightJoin( + * Robots::class, + * "r.id = RobotsParts.robots_id", + * "r" * ); - * + * ``` * - * @param string|array $group - * @return Builder + * @param string $model + * @param string $conditions + * @param string $alias + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function groupBy($group) {} + public function rightJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface {} /** - * Returns the GROUP BY clause + * Set default bind parameters * - * @return string + * @param array $bindParams + * @param bool $merge + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getGroupBy() {} + public function setBindParams(array $bindParams, bool $merge = false): BuilderInterface {} /** - * Returns a PHQL statement built based on the builder parameters + * Set default bind types * - * @return string + * @param array $bindTypes + * @param bool $merge + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public final function getPhql() {} + public function setBindTypes(array $bindTypes, bool $merge = false): BuilderInterface {} /** - * Returns the query built + * Sets the DependencyInjector container * - * @return \Phalcon\Mvc\Model\QueryInterface + * @param \Phalcon\Di\DiInterface $container + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - public function getQuery() {} + public function setDI(\Phalcon\Di\DiInterface $container): BuilderInterface {} /** - * Automatically escapes identifiers but only if they need to be escaped. + * Sets the query WHERE conditions * - * @param string $identifier - * @return string + * ```php + * $builder->where(100); + * + * $builder->where("name = 'Peter'"); + * + * $builder->where( + * "name = :name: AND id > :id:", + * [ + * "name" => "Peter", + * "id" => 100, + * ] + * ); + * ``` + * + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - final public function autoescape($identifier) {} + public function where(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface {} /** * Appends a BETWEEN condition @@ -691,32 +766,32 @@ final public function autoescape($identifier) {} * @param string $expr * @param mixed $minimum * @param mixed $maximum - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - protected function _conditionBetween($clause, $operator, $expr, $minimum, $maximum) {} + protected function conditionBetween(string $clause, string $operator, string $expr, $minimum, $maximum): BuilderInterface {} /** - * Appends a NOT BETWEEN condition + * Appends an IN condition * * @param string $clause * @param string $operator * @param string $expr - * @param mixed $minimum - * @param mixed $maximum - * @return Builder + * @param array $values + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - protected function _conditionNotBetween($clause, $operator, $expr, $minimum, $maximum) {} + protected function conditionIn(string $clause, string $operator, string $expr, array $values): BuilderInterface {} /** - * Appends an IN condition + * Appends a NOT BETWEEN condition * * @param string $clause * @param string $operator * @param string $expr - * @param array $values - * @return Builder + * @param mixed $minimum + * @param mixed $maximum + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - protected function _conditionIn($clause, $operator, $expr, array $values) {} + protected function conditionNotBetween(string $clause, string $operator, string $expr, $minimum, $maximum): BuilderInterface {} /** * Appends a NOT IN condition @@ -725,8 +800,8 @@ protected function _conditionIn($clause, $operator, $expr, array $values) {} * @param string $operator * @param string $expr * @param array $values - * @return Builder + * @return \Phalcon\Mvc\Model\Query\BuilderInterface */ - protected function _conditionNotIn($clause, $operator, $expr, array $values) {} + protected function conditionNotIn(string $clause, string $operator, string $expr, array $values): BuilderInterface {} } diff --git a/src/Phalcon/mvc/model/query/BuilderInterface.php b/src/Phalcon/mvc/model/query/BuilderInterface.php index ced90250..636c17c6 100644 --- a/src/Phalcon/mvc/model/query/BuilderInterface.php +++ b/src/Phalcon/mvc/model/query/BuilderInterface.php @@ -10,151 +10,206 @@ interface BuilderInterface { + const OPERATOR_AND = 'and'; + + const OPERATOR_OR = 'or'; - const OPERATOR_AND = 'and'; + /** + * Add a model to take part of the query + * + * @param string $model + * @param string $alias + * @return BuilderInterface + */ + public function addFrom(string $model, string $alias = null): BuilderInterface; + + /** + * Appends a condition to the current conditions using a AND operator + * + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return BuilderInterface + */ + public function andWhere(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface; + /** + * Appends a BETWEEN condition to the current conditions + * + * @param string $expr + * @param mixed $minimum + * @param mixed $maximum + * @param string $operator + * @return BuilderInterface + */ + public function betweenWhere(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface; /** * Sets the columns to be queried * * @param string|array $columns - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return BuilderInterface */ - public function columns($columns); + public function columns($columns): BuilderInterface; /** - * Return the columns to be queried + * Sets SELECT DISTINCT / SELECT ALL flag * - * @return string|array + * ```php + * $builder->distinct("status"); + * $builder->distinct(null); + * ``` + * + * @param mixed $distinct + * @return BuilderInterface */ - public function getColumns(); + public function distinct($distinct): BuilderInterface; + + /** + * Sets a FOR UPDATE clause + * + * ```php + * $builder->forUpdate(true); + * ``` + * + * @param bool $forUpdate + * @return BuilderInterface + */ + public function forUpdate(bool $forUpdate): BuilderInterface; /** * Sets the models who makes part of the query * * @param string|array $models - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return BuilderInterface */ - public function from($models); + public function from($models): BuilderInterface; /** - * Add a model to take part of the query + * Returns default bind params * - * @param string $model - * @param string $alias - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return array */ - public function addFrom($model, $alias = null); + public function getBindParams(): array; /** - * Return the models who makes part of the query + * Returns default bind types + * + * @return array + */ + public function getBindTypes(): array; + + /** + * Return the columns to be queried * * @return string|array */ - public function getFrom(); + public function getColumns(); /** - * Adds an :type: join (by default type - INNER) to the query + * Returns SELECT DISTINCT / SELECT ALL flag * - * @param string $model - * @param string $conditions - * @param string $alias - * @param string $type - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return bool */ - public function join($model, $conditions = null, $alias = null, $type = null); + public function getDistinct(): bool; /** - * Adds an INNER join to the query + * Return the models who makes part of the query * - * @param string $model - * @param string $conditions - * @param string $alias - * @param string $type - * @return \Phalcon\Mvc\Model\Query\Builder + * @return string|array */ - public function innerJoin($model, $conditions = null, $alias = null); + public function getFrom(); /** - * Adds a LEFT join to the query + * Returns the GROUP BY clause * - * @param string $model - * @param string $conditions - * @param string $alias - * @return \Phalcon\Mvc\Model\Query\Builder + * @return array */ - public function leftJoin($model, $conditions = null, $alias = null); + public function getGroupBy(): array; /** - * Adds a RIGHT join to the query + * Returns the HAVING condition clause * - * @param string $model - * @param string $conditions - * @param string $alias - * @return \Phalcon\Mvc\Model\Query\Builder + * @return string */ - public function rightJoin($model, $conditions = null, $alias = null); + public function getHaving(): string; /** * Return join parts of the query * * @return array */ - public function getJoins(); + public function getJoins(): array; /** - * Sets conditions for the query + * Returns the current LIMIT clause * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return string|array */ - public function where($conditions, $bindParams = null, $bindTypes = null); + public function getLimit(); /** - * Appends a condition to the current conditions using a AND operator + * Returns the current OFFSET clause * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return \Phalcon\Mvc\Model\Query\Builder + * @return int */ - public function andWhere($conditions, $bindParams = null, $bindTypes = null); + public function getOffset(): int; /** - * Appends a condition to the current conditions using an OR operator + * Return the set ORDER BY clause * - * @param string $conditions - * @param array $bindParams - * @param array $bindTypes - * @return \Phalcon\Mvc\Model\Query\Builder + * @return string|array */ - public function orWhere($conditions, $bindParams = null, $bindTypes = null); + public function getOrderBy(); /** - * Appends a BETWEEN condition to the current conditions + * Returns a PHQL statement built based on the builder parameters * - * @param string $expr - * @param mixed $minimum - * @param mixed $maximum - * @param string $operator - * @return \Phalcon\Mvc\Model\Query\Builder + * @return string */ - public function betweenWhere($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND); + public function getPhql(): string; /** - * Appends a NOT BETWEEN condition to the current conditions + * Returns the query built * - * @param string $expr - * @param mixed $minimum - * @param mixed $maximum - * @param string $operator - * @return \Phalcon\Mvc\Model\Query\Builder + * @return \Phalcon\Mvc\Model\QueryInterface + */ + public function getQuery(): QueryInterface; + + /** + * Return the conditions for the query + * + * @return string|array + */ + public function getWhere(); + + /** + * Sets a GROUP BY clause + * + * @param string|array $group + * @return BuilderInterface + */ + public function groupBy($group): BuilderInterface; + + /** + * Sets a HAVING condition clause + * + * @param string $having + * @return BuilderInterface + */ + public function having(string $having): BuilderInterface; + + /** + * Adds an INNER join to the query + * + * @param string $model + * @param string $conditions + * @param string $alias + * @return BuilderInterface */ - public function notBetweenWhere($expr, $minimum, $maximum, $operator = BuilderInterface::OPERATOR_AND); + public function innerJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface; /** * Appends an IN condition to the current conditions @@ -164,98 +219,128 @@ public function notBetweenWhere($expr, $minimum, $maximum, $operator = BuilderIn * @param string $operator * @return BuilderInterface */ - public function inWhere($expr, array $values, $operator = BuilderInterface::OPERATOR_AND); + public function inWhere(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface; /** - * Appends a NOT IN condition to the current conditions + * Adds an :type: join (by default type - INNER) to the query * - * @param string $expr - * @param array $values - * @param string $operator + * @param string $model + * @param string $conditions + * @param string $alias + * @param string $type * @return BuilderInterface */ - public function notInWhere($expr, array $values, $operator = BuilderInterface::OPERATOR_AND); + public function join(string $model, string $conditions = null, string $alias = null): BuilderInterface; /** - * Return the conditions for the query + * Adds a LEFT join to the query * - * @return string|array + * @param string $model + * @param string $conditions + * @param string $alias + * @return BuilderInterface */ - public function getWhere(); + public function leftJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface; /** - * Sets an ORDER BY condition clause + * Sets a LIMIT clause * - * @param string $orderBy - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @param int $limit + * @param int $offset + * @return BuilderInterface */ - public function orderBy($orderBy); + public function limit(int $limit, $offset = null): BuilderInterface; /** - * Return the set ORDER BY clause + * Returns the models involved in the query * - * @return string|array + * @return string|array|null */ - public function getOrderBy(); + public function getModels(); /** - * Sets a HAVING condition clause + * Appends a NOT BETWEEN condition to the current conditions * - * @param string $having - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @param string $expr + * @param mixed $minimum + * @param mixed $maximum + * @param string $operator + * @return BuilderInterface */ - public function having($having); + public function notBetweenWhere(string $expr, $minimum, $maximum, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface; /** - * Returns the HAVING condition clause + * Appends a NOT IN condition to the current conditions * - * @return string|array + * @param string $expr + * @param array $values + * @param string $operator + * @return BuilderInterface */ - public function getHaving(); + public function notInWhere(string $expr, array $values, string $operator = BuilderInterface::OPERATOR_AND): BuilderInterface; /** - * Sets a LIMIT clause + * Sets an OFFSET clause * - * @param int $limit * @param int $offset - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @return BuilderInterface */ - public function limit($limit, $offset = null); + public function offset(int $offset): BuilderInterface; /** - * Returns the current LIMIT clause + * Sets an ORDER BY condition clause * - * @return string|array + * @param string $orderBy + * @return BuilderInterface */ - public function getLimit(); + public function orderBy(string $orderBy): BuilderInterface; /** - * Sets a LIMIT clause + * Appends a condition to the current conditions using an OR operator * - * @param string|array $group - * @return \Phalcon\Mvc\Model\Query\BuilderInterface + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return BuilderInterface */ - public function groupBy($group); + public function orWhere(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface; /** - * Returns the GROUP BY clause + * Adds a RIGHT join to the query * - * @return string + * @param string $model + * @param string $conditions + * @param string $alias + * @return BuilderInterface */ - public function getGroupBy(); + public function rightJoin(string $model, string $conditions = null, string $alias = null): BuilderInterface; /** - * Returns a PHQL statement built based on the builder parameters + * Set default bind parameters * - * @return string + * @param array $bindParams + * @param bool $merge + * @return BuilderInterface */ - public function getPhql(); + public function setBindParams(array $bindParams, bool $merge = false): BuilderInterface; /** - * Returns the query built + * Set default bind types * - * @return \Phalcon\Mvc\Model\QueryInterface + * @param array $bindTypes + * @param bool $merge + * @return BuilderInterface + */ + public function setBindTypes(array $bindTypes, bool $merge = false): BuilderInterface; + + /** + * Sets conditions for the query + * + * @param string $conditions + * @param array $bindParams + * @param array $bindTypes + * @return BuilderInterface */ - public function getQuery(); + public function where(string $conditions, array $bindParams = array(), array $bindTypes = array()): BuilderInterface; } diff --git a/src/Phalcon/mvc/model/query/Lang.php b/src/Phalcon/mvc/model/query/Lang.php index 5f453526..28727de1 100644 --- a/src/Phalcon/mvc/model/query/Lang.php +++ b/src/Phalcon/mvc/model/query/Lang.php @@ -15,9 +15,11 @@ * the same technology as SQLite. This technology provides a small in-memory * parser with a very low memory footprint that is also thread-safe. * - * - * $intermediate = Phalcon\Mvc\Model\Query\Lang::parsePHQL("SELECT r. FROM Robots r LIMIT 10"); - * + * ```php + * $intermediate = Phalcon\Mvc\Model\Query\Lang::parsePHQL( + * "SELECT r. FROM Robots r LIMIT 10" + * ); + * ``` */ abstract class Lang { @@ -28,6 +30,6 @@ abstract class Lang * @param string $phql * @return string */ - public static function parsePHQL($phql) {} + public static function parsePHQL(string $phql): string {} } diff --git a/src/Phalcon/mvc/model/query/Status.php b/src/Phalcon/mvc/model/query/Status.php index ba75ee6d..f902467d 100644 --- a/src/Phalcon/mvc/model/query/Status.php +++ b/src/Phalcon/mvc/model/query/Status.php @@ -10,7 +10,7 @@ * information and the related messages produced by the * model which finally executes the operations when it fails * - * + * ```php * $phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:"; * * $status = $app->modelsManager->executeQuery( @@ -24,18 +24,18 @@ * ); * * // Check if the update was successful - * if ($status->success() === true) { + * if ($status->success()) { * echo "OK"; * } - * + * ``` */ class Status implements \Phalcon\Mvc\Model\Query\StatusInterface { - protected $_success; + protected $model; - protected $_model; + protected $success; /** @@ -44,27 +44,27 @@ class Status implements \Phalcon\Mvc\Model\Query\StatusInterface * @param bool $success * @param \Phalcon\Mvc\ModelInterface $model */ - public function __construct($success, \Phalcon\Mvc\ModelInterface $model = null) {} + public function __construct(bool $success, \Phalcon\Mvc\ModelInterface $model = null) {} /** - * Returns the model that executed the action + * Returns the messages produced because of a failed operation * - * @return \Phalcon\Mvc\ModelInterface + * @return array|\Phalcon\Messages\MessageInterface[] */ - public function getModel() {} + public function getMessages(): array {} /** - * Returns the messages produced because of a failed operation + * Returns the model that executed the action * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return \Phalcon\Mvc\ModelInterface */ - public function getMessages() {} + public function getModel(): ModelInterface {} /** * Allows to check if the executed operation was successful * * @return bool */ - public function success() {} + public function success(): bool {} } diff --git a/src/Phalcon/mvc/model/query/StatusInterface.php b/src/Phalcon/mvc/model/query/StatusInterface.php index b2980bec..1f16632c 100644 --- a/src/Phalcon/mvc/model/query/StatusInterface.php +++ b/src/Phalcon/mvc/model/query/StatusInterface.php @@ -11,24 +11,24 @@ interface StatusInterface { /** - * Returns the model which executed the action + * Returns the messages produced by an operation failed * - * @return \Phalcon\Mvc\ModelInterface + * @return array|\Phalcon\Messages\MessageInterface[] */ - public function getModel(); + public function getMessages(): array; /** - * Returns the messages produced by an operation failed + * Returns the model which executed the action * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return \Phalcon\Mvc\ModelInterface */ - public function getMessages(); + public function getModel(): ModelInterface; /** * Allows to check if the executed operation was successful * * @return bool */ - public function success(); + public function success(): bool; } diff --git a/src/Phalcon/mvc/model/resultset/Complex.php b/src/Phalcon/mvc/model/resultset/Complex.php index 793e38d0..7f057733 100644 --- a/src/Phalcon/mvc/model/resultset/Complex.php +++ b/src/Phalcon/mvc/model/resultset/Complex.php @@ -11,12 +11,13 @@ class Complex extends \Phalcon\Mvc\Model\Resultset implements \Phalcon\Mvc\Model\ResultsetInterface { - protected $_columnTypes; + protected $columnTypes; /** - * Unserialised result-set hydrated all rows already. unserialise() sets _disableHydration to true + * Unserialised result-set hydrated all rows already. unserialise() sets + * disableHydration to true */ - protected $_disableHydration = false; + protected $disableHydration = false; /** @@ -24,31 +25,31 @@ class Complex extends \Phalcon\Mvc\Model\Resultset implements \Phalcon\Mvc\Model * * @param array $columnTypes * @param \Phalcon\Db\ResultInterface $result - * @param \Phalcon\Cache\BackendInterface $cache + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache */ - public function __construct($columnTypes, \Phalcon\Db\ResultInterface $result = null, \Phalcon\Cache\BackendInterface $cache = null) {} + public function __construct($columnTypes, \Phalcon\Db\ResultInterface $result = null, \Phalcon\Cache\Adapter\AdapterInterface $cache = null) {} /** * Returns current row in the resultset * * @return bool|ModelInterface */ - public final function current() {} + final public function current() {} /** - * Returns a complete resultset as an array, if the resultset has a big number of rows - * it could consume more memory than currently it does. + * Returns a complete resultset as an array, if the resultset has a big + * number of rows it could consume more memory than currently it does. * * @return array */ - public function toArray() {} + public function toArray(): array {} /** * Serializing a resultset will dump all related rows into a big array * * @return string */ - public function serialize() {} + public function serialize(): string {} /** * Unserializing a resultset will allow to only works on the rows present in the saved state diff --git a/src/Phalcon/mvc/model/resultset/Simple.php b/src/Phalcon/mvc/model/resultset/Simple.php index 8d377287..1209af8a 100644 --- a/src/Phalcon/mvc/model/resultset/Simple.php +++ b/src/Phalcon/mvc/model/resultset/Simple.php @@ -11,13 +11,15 @@ class Simple extends \Phalcon\Mvc\Model\Resultset { - protected $_model; + protected $columnMap; - protected $_columnMap; + protected $model; - - protected $_keepSnapshots = false; + /** + * @var bool + */ + protected $keepSnapshots = false; /** @@ -25,38 +27,40 @@ class Simple extends \Phalcon\Mvc\Model\Resultset * * @param array $columnMap * @param \Phalcon\Mvc\ModelInterface|Phalcon\Mvc\Model\Row $model - * @param \Phalcon\Db\Result\Pdo|null $result - * @param \Phalcon\Cache\BackendInterface $cache - * @param boolean $keepSnapshots + * @param mixed $result + * @param \Phalcon\Cache\Adapter\AdapterInterface $cache + * @param bool $keepSnapshots */ - public function __construct($columnMap, $model, $result, \Phalcon\Cache\BackendInterface $cache = null, $keepSnapshots = null) {} + public function __construct($columnMap, $model, $result, \Phalcon\Cache\Adapter\AdapterInterface $cache = null, bool $keepSnapshots = null) {} /** * Returns current row in the resultset * - * @return bool|ModelInterface + * @return null|ModelInterface */ - public final function current() {} + final public function current(): ?ModelInterface {} /** - * Returns a complete resultset as an array, if the resultset has a big number of rows - * it could consume more memory than currently it does. Export the resultset to an array - * couldn't be faster with a large number of records + * Returns a complete resultset as an array, if the resultset has a big + * number of rows it could consume more memory than currently it does. + * Export the resultset to an array couldn't be faster with a large number + * of records * * @param bool $renameColumns * @return array */ - public function toArray($renameColumns = true) {} + public function toArray(bool $renameColumns = true): array {} /** * Serializing a resultset will dump all related rows into a big array * * @return string */ - public function serialize() {} + public function serialize(): string {} /** - * Unserializing a resultset will allow to only works on the rows present in the saved state + * Unserializing a resultset will allow to only works on the rows present in + * the saved state * * @param mixed $data */ diff --git a/src/Phalcon/mvc/model/transaction/Failed.php b/src/Phalcon/mvc/model/transaction/Failed.php index 725b413e..08fa28f4 100644 --- a/src/Phalcon/mvc/model/transaction/Failed.php +++ b/src/Phalcon/mvc/model/transaction/Failed.php @@ -10,7 +10,7 @@ class Failed extends \Phalcon\Mvc\Model\Transaction\Exception { - protected $_record = null; + protected $record = null; /** @@ -19,20 +19,20 @@ class Failed extends \Phalcon\Mvc\Model\Transaction\Exception * @param string $message * @param \Phalcon\Mvc\ModelInterface $record */ - public function __construct($message, \Phalcon\Mvc\ModelInterface $record = null) {} + public function __construct(string $message, \Phalcon\Mvc\ModelInterface $record = null) {} /** * Returns validation record messages which stop the transaction * - * @return \Phalcon\Mvc\Model\MessageInterface[] + * @return \Phalcon\Mvc\ModelInterface */ - public function getRecordMessages() {} + public function getRecord(): ModelInterface {} /** * Returns validation record messages which stop the transaction * - * @return \Phalcon\Mvc\ModelInterface + * @return array|\Phalcon\Messages\MessageInterface[] */ - public function getRecord() {} + public function getRecordMessages(): array {} } diff --git a/src/Phalcon/mvc/model/transaction/Manager.php b/src/Phalcon/mvc/model/transaction/Manager.php index faf1aa4a..31af4afd 100644 --- a/src/Phalcon/mvc/model/transaction/Manager.php +++ b/src/Phalcon/mvc/model/transaction/Manager.php @@ -5,14 +5,15 @@ /** * Phalcon\Mvc\Model\Transaction\Manager * - * A transaction acts on a single database connection. If you have multiple class-specific - * databases, the transaction will not protect interaction among them. + * A transaction acts on a single database connection. If you have multiple + * class-specific databases, the transaction will not protect interaction among + * them. * * This class manages the objects that compose a transaction. - * A transaction produces a unique connection that is passed to every - * object part of the transaction. + * A transaction produces a unique connection that is passed to every object + * part of the transaction. * - * + * ```php * use Phalcon\Mvc\Model\Transaction\Failed; * use Phalcon\Mvc\Model\Transaction\Manager; * @@ -28,7 +29,7 @@ * $robot->name = "WALL·E"; * $robot->created_at = date("Y-m-d"); * - * if ($robot->save() === false){ + * if ($robot->save() === false) { * $transaction->rollback("Can't save robot"); * } * @@ -46,146 +47,150 @@ * } catch (Failed $e) { * echo "Failed, reason: ", $e->getMessage(); * } - * + * ``` */ class Manager implements \Phalcon\Mvc\Model\Transaction\ManagerInterface, \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; + protected $container; - protected $_initialized = false; + protected $initialized = false; - protected $_rollbackPendent = true; + protected $number = 0; - protected $_number = 0; + protected $rollbackPendent = true; - protected $_service = 'db'; + protected $service = 'db'; - - protected $_transactions; + /** + * @var array + */ + protected $transactions = array(); /** * Phalcon\Mvc\Model\Transaction\Manager constructor * - * @param \Phalcon\DiInterface $dependencyInjector + * @param \Phalcon\Di\DiInterface $container */ - public function __construct(\Phalcon\DiInterface $dependencyInjector = null) {} + public function __construct(\Phalcon\Di\DiInterface $container = null) {} /** - * Sets the dependency injection container - * - * @param \Phalcon\DiInterface $dependencyInjector + * Remove all the transactions from the manager */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} + public function collectTransactions() {} /** - * Returns the dependency injection container - * - * @return \Phalcon\DiInterface + * Commits active transactions within the manager */ - public function getDI() {} + public function commit() {} /** - * Sets the database service used to run the isolated transactions + * Returns a new \Phalcon\Mvc\Model\Transaction or an already created once + * This method registers a shutdown function to rollback active connections * - * @param string $service - * @return Manager + * @param bool $autoBegin + * @return \Phalcon\Mvc\Model\TransactionInterface */ - public function setDbService($service) {} + public function get(bool $autoBegin = true): TransactionInterface {} /** * Returns the database service used to isolate the transaction * * @return string */ - public function getDbService() {} + public function getDbService(): string {} /** - * Set if the transaction manager must register a shutdown function to clean up pendent transactions + * Returns the dependency injection container * - * @param bool $rollbackPendent - * @return Manager + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Create/Returns a new transaction or an existing one + * + * @param bool $autoBegin + * @return \Phalcon\Mvc\Model\TransactionInterface */ - public function setRollbackPendent($rollbackPendent) {} + public function getOrCreateTransaction(bool $autoBegin = true): TransactionInterface {} /** - * Check if the transaction manager is registering a shutdown function to clean up pendent transactions + * Check if the transaction manager is registering a shutdown function to + * clean up pendent transactions * * @return bool */ - public function getRollbackPendent() {} + public function getRollbackPendent(): bool {} /** * Checks whether the manager has an active transaction * * @return bool */ - public function has() {} + public function has(): bool {} /** - * Returns a new \Phalcon\Mvc\Model\Transaction or an already created once - * This method registers a shutdown function to rollback active connections + * Notifies the manager about a committed transaction * - * @param bool $autoBegin - * @return \Phalcon\Mvc\Model\TransactionInterface + * @param \Phalcon\Mvc\Model\TransactionInterface $transaction */ - public function get($autoBegin = true) {} + public function notifyCommit(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} /** - * Create/Returns a new transaction or an existing one + * Notifies the manager about a rollbacked transaction * - * @param bool $autoBegin - * @return \Phalcon\Mvc\Model\TransactionInterface + * @param \Phalcon\Mvc\Model\TransactionInterface $transaction */ - public function getOrCreateTransaction($autoBegin = true) {} + public function notifyRollback(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} /** * Rollbacks active transactions within the manager + * Collect will remove the transaction from the manager + * + * @param bool $collect */ - public function rollbackPendent() {} + public function rollback(bool $collect = true) {} /** - * Commits active transactions within the manager + * Rollbacks active transactions within the manager */ - public function commit() {} + public function rollbackPendent() {} /** - * Rollbacks active transactions within the manager - * Collect will remove the transaction from the manager + * Sets the database service used to run the isolated transactions * - * @param boolean $collect + * @param string $service + * @return \Phalcon\Mvc\Model\Transaction\ManagerInterface */ - public function rollback($collect = true) {} + public function setDbService(string $service): ManagerInterface {} /** - * Notifies the manager about a rollbacked transaction + * Sets the dependency injection container * - * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @param \Phalcon\Di\DiInterface $container */ - public function notifyRollback(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} /** - * Notifies the manager about a committed transaction + * Set if the transaction manager must register a shutdown function to clean + * up pendent transactions * - * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @param bool $rollbackPendent + * @return \Phalcon\Mvc\Model\Transaction\ManagerInterface */ - public function notifyCommit(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} + public function setRollbackPendent(bool $rollbackPendent): ManagerInterface {} /** * Removes transactions from the TransactionManager * * @param \Phalcon\Mvc\Model\TransactionInterface $transaction */ - protected function _collectTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} - - /** - * Remove all the transactions from the manager - */ - public function collectTransactions() {} + protected function collectTransaction(\Phalcon\Mvc\Model\TransactionInterface $transaction) {} } diff --git a/src/Phalcon/mvc/model/transaction/ManagerInterface.php b/src/Phalcon/mvc/model/transaction/ManagerInterface.php index d2c1b841..21fa668d 100644 --- a/src/Phalcon/mvc/model/transaction/ManagerInterface.php +++ b/src/Phalcon/mvc/model/transaction/ManagerInterface.php @@ -11,11 +11,14 @@ interface ManagerInterface { /** - * Checks whether manager has an active transaction - * - * @return bool + * Remove all the transactions from the manager + */ + public function collectTransactions(); + + /** + * Commits active transactions within the manager */ - public function has(); + public function commit(); /** * Returns a new \Phalcon\Mvc\Model\Transaction or an already created once @@ -23,25 +26,35 @@ public function has(); * @param bool $autoBegin * @return \Phalcon\Mvc\Model\TransactionInterface */ - public function get($autoBegin = true); + public function get(bool $autoBegin = true): TransactionInterface; /** - * Rollbacks active transactions within the manager + * Returns the database service used to isolate the transaction + * + * @return string */ - public function rollbackPendent(); + public function getDbService(): string; /** - * Commits active transactions within the manager + * Check if the transaction manager is registering a shutdown function to clean up pendent transactions + * + * @return bool */ - public function commit(); + public function getRollbackPendent(): bool; /** - * Rollbacks active transactions within the manager - * Collect will remove transaction from the manager + * Checks whether manager has an active transaction * - * @param boolean $collect + * @return bool */ - public function rollback($collect = false); + public function has(): bool; + + /** + * Notifies the manager about a committed transaction + * + * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + */ + public function notifyCommit(\Phalcon\Mvc\Model\TransactionInterface $transaction); /** * Notifies the manager about a rollbacked transaction @@ -51,15 +64,32 @@ public function rollback($collect = false); public function notifyRollback(\Phalcon\Mvc\Model\TransactionInterface $transaction); /** - * Notifies the manager about a committed transaction + * Rollbacks active transactions within the manager + * Collect will remove transaction from the manager * - * @param \Phalcon\Mvc\Model\TransactionInterface $transaction + * @param bool $collect */ - public function notifyCommit(\Phalcon\Mvc\Model\TransactionInterface $transaction); + public function rollback(bool $collect = false); /** - * Remove all the transactions from the manager + * Rollbacks active transactions within the manager */ - public function collectTransactions(); + public function rollbackPendent(); + + /** + * Sets the database service used to run the isolated transactions + * + * @param string $service + * @return ManagerInterface + */ + public function setDbService(string $service): ManagerInterface; + + /** + * Set if the transaction manager must register a shutdown function to clean up pendent transactions + * + * @param bool $rollbackPendent + * @return ManagerInterface + */ + public function setRollbackPendent(bool $rollbackPendent): ManagerInterface; } diff --git a/src/Phalcon/mvc/model/validator/Email.php b/src/Phalcon/mvc/model/validator/Email.php deleted file mode 100644 index 62825bce..00000000 --- a/src/Phalcon/mvc/model/validator/Email.php +++ /dev/null @@ -1,49 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\Email as EmailValidator; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new EmailValidator( - * [ - * "field" => "electronic_mail", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\Email - */ -class Email extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Exclusionin.php b/src/Phalcon/mvc/model/validator/Exclusionin.php deleted file mode 100644 index cd444ce3..00000000 --- a/src/Phalcon/mvc/model/validator/Exclusionin.php +++ /dev/null @@ -1,50 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionInValidator; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new ExclusionInValidator( - * [ - * "field" => "status", - * "domain" => ["A", "I"], - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\EclusionIn - */ -class Exclusionin extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Inclusionin.php b/src/Phalcon/mvc/model/validator/Inclusionin.php deleted file mode 100644 index d506ab45..00000000 --- a/src/Phalcon/mvc/model/validator/Inclusionin.php +++ /dev/null @@ -1,50 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\InclusionIn as InclusionInValidator; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new InclusionInValidator( - * [ - * "field" => "status", - * "domain" => ["A", "I"], - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\InclusionIn - */ -class Inclusionin extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Ip.php b/src/Phalcon/mvc/model/validator/Ip.php deleted file mode 100644 index f6ca5e5d..00000000 --- a/src/Phalcon/mvc/model/validator/Ip.php +++ /dev/null @@ -1,82 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\Ip; - * - * class Data extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * // Any pubic IP - * $this->validate( - * new IP( - * [ - * "field" => "server_ip", - * "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - * "allowReserved" => false, // False if not specified. Ignored for v6 - * "allowPrivate" => false, // False if not specified - * "message" => "IP address has to be correct", - * ] - * ) - * ); - * - * // Any public v4 address - * $this->validate( - * new IP( - * [ - * "field" => "ip_4", - * "version" => IP::VERSION_4, - * "message" => "IP address has to be correct", - * ] - * ) - * ); - * - * // Any v6 address - * $this->validate( - * new IP( - * [ - * "field" => "ip6", - * "version" => IP::VERSION_6, - * "allowPrivate" => true, - * "message" => "IP address has to be correct", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - */ -class Ip extends \Phalcon\Mvc\Model\Validator -{ - - const VERSION_4 = 1048576; - - - const VERSION_6 = 2097152; - - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Numericality.php b/src/Phalcon/mvc/model/validator/Numericality.php deleted file mode 100644 index 9878eac2..00000000 --- a/src/Phalcon/mvc/model/validator/Numericality.php +++ /dev/null @@ -1,49 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\Numericality as NumericalityValidator; - * - * class Products extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new NumericalityValidator( - * [ - * "field" => "price", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\Numericality - */ -class Numericality extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/PresenceOf.php b/src/Phalcon/mvc/model/validator/PresenceOf.php deleted file mode 100644 index 229e417c..00000000 --- a/src/Phalcon/mvc/model/validator/PresenceOf.php +++ /dev/null @@ -1,50 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\PresenceOf; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new PresenceOf( - * [ - * "field" => "name", - * "message" => "The name is required", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\PresenceOf - */ -class PresenceOf extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Regex.php b/src/Phalcon/mvc/model/validator/Regex.php deleted file mode 100644 index 64b6ee12..00000000 --- a/src/Phalcon/mvc/model/validator/Regex.php +++ /dev/null @@ -1,50 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\Regex as RegexValidator; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new RegexValidator( - * [ - * "field" => "created_at", - * "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])/", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() == true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\Regex - */ -class Regex extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/StringLength.php b/src/Phalcon/mvc/model/validator/StringLength.php deleted file mode 100644 index 91a7701f..00000000 --- a/src/Phalcon/mvc/model/validator/StringLength.php +++ /dev/null @@ -1,53 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\StringLength as StringLengthValidator; - * - * class Subscriptors extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new StringLengthValidator( - * [ - * "field" => "name_last", - * "max" => 50, - * "min" => 2, - * "messageMaximum" => "We don't like really long names", - * "messageMinimum" => "We want more than just their initials", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\StringLength - */ -class StringLength extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Uniqueness.php b/src/Phalcon/mvc/model/validator/Uniqueness.php deleted file mode 100644 index c9cb687b..00000000 --- a/src/Phalcon/mvc/model/validator/Uniqueness.php +++ /dev/null @@ -1,52 +0,0 @@ - - * use Phalcon\Mvc\Collection; - * use Phalcon\Mvc\Model\Validator\Uniqueness; - * - * class Subscriptors extends Collection - * { - * public function validation() - * { - * $this->validate( - * new Uniqueness( - * [ - * "field" => "email", - * "message" => "Value of field 'email' is already present in another record", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\Uniqueness - */ -class Uniqueness extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/model/validator/Url.php b/src/Phalcon/mvc/model/validator/Url.php deleted file mode 100644 index 28ee074f..00000000 --- a/src/Phalcon/mvc/model/validator/Url.php +++ /dev/null @@ -1,49 +0,0 @@ - - * use Phalcon\Mvc\Model\Validator\Url as UrlValidator; - * - * class Posts extends \Phalcon\Mvc\Collection - * { - * public function validation() - * { - * $this->validate( - * new UrlValidator( - * [ - * "field" => "source_url", - * ] - * ) - * ); - * - * if ($this->validationHasFailed() === true) { - * return false; - * } - * } - * } - * - * - * @deprecated 3.1.0 - * @see Phalcon\Validation\Validator\Url - */ -class Url extends \Phalcon\Mvc\Model\Validator -{ - - /** - * Executes the validator - * - * @param \Phalcon\Mvc\EntityInterface $record - * @return bool - */ - public function validate(\Phalcon\Mvc\EntityInterface $record) {} - -} diff --git a/src/Phalcon/mvc/router/Annotations.php b/src/Phalcon/mvc/router/Annotations.php index 18c4db8c..b8adad00 100644 --- a/src/Phalcon/mvc/router/Annotations.php +++ b/src/Phalcon/mvc/router/Annotations.php @@ -7,7 +7,7 @@ * * A router that reads routes annotations from classes/resources * - * + * ```php * use Phalcon\Mvc\Router\Annotations; * * $di->setShared( @@ -22,59 +22,58 @@ * return $router; * } * ); - * + * ``` */ class Annotations extends \Phalcon\Mvc\Router { - protected $_handlers = array(); + protected $actionSuffix = 'Action'; - protected $_controllerSuffix = 'Controller'; + protected $controllerSuffix = 'Controller'; - protected $_actionSuffix = 'Action'; + protected $handlers = array(); - protected $_routePrefix; + protected $routePrefix; /** * Adds a resource to the annotations handler * A resource is a class that contains routing annotations + * The class is located in a module * + * @param string $module * @param string $handler * @param string $prefix * @return Annotations */ - public function addResource($handler, $prefix = null) {} + public function addModuleResource(string $module, string $handler, string $prefix = null): Annotations {} /** * Adds a resource to the annotations handler * A resource is a class that contains routing annotations - * The class is located in a module * - * @param string $module * @param string $handler * @param string $prefix * @return Annotations */ - public function addModuleResource($module, $handler, $prefix = null) {} + public function addResource(string $handler, string $prefix = null): Annotations {} /** - * Produce the routing parameters from the rewrite information + * Return the registered resources * - * @param string $uri + * @return array */ - public function handle($uri = null) {} + public function getResources(): array {} /** - * Checks for annotations in the controller docblock + * Produce the routing parameters from the rewrite information * - * @param string $handler - * @param \Phalcon\Annotations\Annotation $annotation + * @param string $uri */ - public function processControllerAnnotation($handler, \Phalcon\Annotations\Annotation $annotation) {} + public function handle(string $uri) {} /** * Checks for annotations in the public methods of the controller @@ -85,27 +84,28 @@ public function processControllerAnnotation($handler, \Phalcon\Annotations\Annot * @param string $action * @param \Phalcon\Annotations\Annotation $annotation */ - public function processActionAnnotation($module, $namespaceName, $controller, $action, \Phalcon\Annotations\Annotation $annotation) {} + public function processActionAnnotation(string $module, string $namespaceName, string $controller, string $action, \Phalcon\Annotations\Annotation $annotation) {} /** - * Changes the controller class suffix + * Checks for annotations in the controller docblock * - * @param string $controllerSuffix + * @param string $handler + * @param \Phalcon\Annotations\Annotation $annotation */ - public function setControllerSuffix($controllerSuffix) {} + public function processControllerAnnotation(string $handler, \Phalcon\Annotations\Annotation $annotation) {} /** * Changes the action method suffix * * @param string $actionSuffix */ - public function setActionSuffix($actionSuffix) {} + public function setActionSuffix(string $actionSuffix) {} /** - * Return the registered resources + * Changes the controller class suffix * - * @return array + * @param string $controllerSuffix */ - public function getResources() {} + public function setControllerSuffix(string $controllerSuffix) {} } diff --git a/src/Phalcon/mvc/router/Group.php b/src/Phalcon/mvc/router/Group.php index e89389c2..864e7821 100644 --- a/src/Phalcon/mvc/router/Group.php +++ b/src/Phalcon/mvc/router/Group.php @@ -7,7 +7,7 @@ * * Helper class to create a group of routes with common attributes * - * + * ```php * $router = new \Phalcon\Mvc\Router(); * * //Create a group with a common module and controller @@ -48,24 +48,24 @@ * * //Add the group to the router * $router->mount($blog); - * + * ``` */ class Group implements \Phalcon\Mvc\Router\GroupInterface { - protected $_prefix; + protected $beforeMatch; - protected $_hostname; + protected $hostname; - protected $_paths; + protected $paths; - protected $_routes; + protected $prefix; - protected $_beforeMatch; + protected $routes; /** @@ -76,155 +76,182 @@ class Group implements \Phalcon\Mvc\Router\GroupInterface public function __construct($paths = null) {} /** - * Set a hostname restriction for all the routes in the group + * Adds a route to the router on any HTTP method * - * @param string $hostname - * @return GroupInterface + * ```php + * $router->add("/about", "About::index"); + * ``` + * + * @param string $pattern + * @param mixed $paths + * @param mixed $httpMethods + * @return RouteInterface */ - public function setHostname($hostname) {} + public function add(string $pattern, $paths = null, $httpMethods = null): RouteInterface {} /** - * Returns the hostname restriction + * Adds a route to the router that only match if the HTTP method is CONNECT * - * @return string + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function getHostname() {} + public function addConnect(string $pattern, $paths = null): RouteInterface {} /** - * Set a common uri prefix for all the routes in this group + * Adds a route to the router that only match if the HTTP method is DELETE * - * @param string $prefix - * @return GroupInterface + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function setPrefix($prefix) {} + public function addDelete(string $pattern, $paths = null): RouteInterface {} /** - * Returns the common prefix for all the routes + * Adds a route to the router that only match if the HTTP method is GET * - * @return string + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function getPrefix() {} + public function addGet(string $pattern, $paths = null): RouteInterface {} /** - * Sets a callback that is called if the route is matched. - * The developer can implement any arbitrary conditions here - * If the callback returns false the route is treated as not matched + * Adds a route to the router that only match if the HTTP method is HEAD * - * @param callable $beforeMatch - * @return GroupInterface + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function beforeMatch($beforeMatch) {} + public function addHead(string $pattern, $paths = null): RouteInterface {} /** - * Returns the 'before match' callback if any + * Add a route to the router that only match if the HTTP method is OPTIONS * - * @return callable + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function getBeforeMatch() {} + public function addOptions(string $pattern, $paths = null): RouteInterface {} /** - * Set common paths for all the routes in the group + * Adds a route to the router that only match if the HTTP method is PATCH * - * @param mixed $paths - * @return GroupInterface + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function setPaths($paths) {} + public function addPatch(string $pattern, $paths = null): RouteInterface {} /** - * Returns the common paths defined for this group + * Adds a route to the router that only match if the HTTP method is POST * - * @return array|string + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function getPaths() {} + public function addPost(string $pattern, $paths = null): RouteInterface {} /** - * Returns the routes added to the group + * Adds a route to the router that only match if the HTTP method is PURGE * - * @return RouteInterface[] + * @param string $pattern + * @param string|array $paths + * @return RouteInterface */ - public function getRoutes() {} + public function addPurge(string $pattern, $paths = null): RouteInterface {} /** - * Adds a route to the router on any HTTP method - * - * - * $router->add("/about", "About::index"); - * + * Adds a route to the router that only match if the HTTP method is PUT * * @param string $pattern - * @param mixed $paths - * @param mixed $httpMethods + * @param string|array $paths * @return RouteInterface */ - public function add($pattern, $paths = null, $httpMethods = null) {} + public function addPut(string $pattern, $paths = null): RouteInterface {} /** - * Adds a route to the router that only match if the HTTP method is GET + * Adds a route to the router that only match if the HTTP method is TRACE * * @param string $pattern - * @param string/array $paths + * @param string|array $paths * @return RouteInterface */ - public function addGet($pattern, $paths = null) {} + public function addTrace(string $pattern, $paths = null): RouteInterface {} /** - * Adds a route to the router that only match if the HTTP method is POST + * Sets a callback that is called if the route is matched. + * The developer can implement any arbitrary conditions here + * If the callback returns false the route is treated as not matched * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @param callable $beforeMatch + * @return GroupInterface */ - public function addPost($pattern, $paths = null) {} + public function beforeMatch($beforeMatch): GroupInterface {} /** - * Adds a route to the router that only match if the HTTP method is PUT + * Removes all the pre-defined routes + */ + public function clear() {} + + /** + * Returns the 'before match' callback if any * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @return callable */ - public function addPut($pattern, $paths = null) {} + public function getBeforeMatch() {} /** - * Adds a route to the router that only match if the HTTP method is PATCH + * Returns the hostname restriction * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @return string */ - public function addPatch($pattern, $paths = null) {} + public function getHostname(): string {} /** - * Adds a route to the router that only match if the HTTP method is DELETE + * Returns the common paths defined for this group * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @return array|string */ - public function addDelete($pattern, $paths = null) {} + public function getPaths() {} /** - * Add a route to the router that only match if the HTTP method is OPTIONS + * Returns the common prefix for all the routes * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @return string */ - public function addOptions($pattern, $paths = null) {} + public function getPrefix(): string {} /** - * Adds a route to the router that only match if the HTTP method is HEAD + * Returns the routes added to the group * - * @param string $pattern - * @param string/array $paths - * @return RouteInterface + * @return array|RouteInterface[] */ - public function addHead($pattern, $paths = null) {} + public function getRoutes(): array {} /** - * Removes all the pre-defined routes + * Set a hostname restriction for all the routes in the group + * + * @param string $hostname + * @return GroupInterface */ - public function clear() {} + public function setHostname(string $hostname): GroupInterface {} + + /** + * Set common paths for all the routes in the group + * + * @param mixed $paths + * @return GroupInterface + */ + public function setPaths($paths): GroupInterface {} + + /** + * Set a common uri prefix for all the routes in this group + * + * @param string $prefix + * @return GroupInterface + */ + public function setPrefix(string $prefix): GroupInterface {} /** * Adds a route applying the common attributes @@ -234,6 +261,6 @@ public function clear() {} * @param mixed $httpMethods * @return RouteInterface */ - protected function _addRoute($pattern, $paths = null, $httpMethods = null) {} + protected function addRoute(string $pattern, $paths = null, $httpMethods = null): RouteInterface {} } diff --git a/src/Phalcon/mvc/router/GroupInterface.php b/src/Phalcon/mvc/router/GroupInterface.php index dd9a10b1..33d59115 100644 --- a/src/Phalcon/mvc/router/GroupInterface.php +++ b/src/Phalcon/mvc/router/GroupInterface.php @@ -5,7 +5,7 @@ /** * Phalcon\Mvc\Router\GroupInterface * - * + * ```php * $router = new \Phalcon\Mvc\Router(); * * // Create a group with a common module and controller @@ -46,160 +46,187 @@ * * // Add the group to the router * $router->mount($blog); - * + * ``` */ interface GroupInterface { /** - * Set a hostname restriction for all the routes in the group + * Adds a route to the router on any HTTP method * - * @param string $hostname - * @return GroupInterface - */ - public function setHostname($hostname); - - /** - * Returns the hostname restriction + * ```php + * router->add("/about", "About::index"); + * ``` * - * @return string + * @param string $pattern + * @param mixed $paths + * @param mixed $httpMethods + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getHostname(); + public function add(string $pattern, $paths = null, $httpMethods = null): RouteInterface; /** - * Set a common uri prefix for all the routes in this group + * Adds a route to the router that only match if the HTTP method is CONNECT * - * @param string $prefix - * @return GroupInterface + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setPrefix($prefix); + public function addConnect(string $pattern, $paths = null): RouteInterface; /** - * Returns the common prefix for all the routes + * Adds a route to the router that only match if the HTTP method is DELETE * - * @return string + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getPrefix(); + public function addDelete(string $pattern, $paths = null): RouteInterface; /** - * Sets a callback that is called if the route is matched. - * The developer can implement any arbitrary conditions here - * If the callback returns false the route is treated as not matched + * Adds a route to the router that only match if the HTTP method is GET * - * @param callable $beforeMatch - * @return GroupInterface + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function beforeMatch($beforeMatch); + public function addGet(string $pattern, $paths = null): RouteInterface; /** - * Returns the 'before match' callback if any + * Adds a route to the router that only match if the HTTP method is HEAD * - * @return callable + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getBeforeMatch(); + public function addHead(string $pattern, $paths = null): RouteInterface; /** - * Set common paths for all the routes in the group + * Add a route to the router that only match if the HTTP method is OPTIONS * - * @param array $paths - * @return GroupInterface + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function setPaths($paths); + public function addOptions(string $pattern, $paths = null): RouteInterface; /** - * Returns the common paths defined for this group + * Adds a route to the router that only match if the HTTP method is PATCH * - * @return array|string + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getPaths(); + public function addPatch(string $pattern, $paths = null): RouteInterface; /** - * Returns the routes added to the group + * Adds a route to the router that only match if the HTTP method is POST * - * @return \Phalcon\Mvc\Router\RouteInterface[] + * @param string $pattern + * @param mixed $paths + * @return \Phalcon\Mvc\Router\RouteInterface */ - public function getRoutes(); + public function addPost(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router on any HTTP method - * - * - * router->add("/about", "About::index"); - * + * Adds a route to the router that only match if the HTTP method is PURGE * * @param string $pattern * @param mixed $paths - * @param mixed $httpMethods * @return \Phalcon\Mvc\Router\RouteInterface */ - public function add($pattern, $paths = null, $httpMethods = null); + public function addPurge(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is GET + * Adds a route to the router that only match if the HTTP method is PUT * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addGet($pattern, $paths = null); + public function addPut(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is POST + * Adds a route to the router that only match if the HTTP method is TRACE * * @param string $pattern * @param mixed $paths * @return \Phalcon\Mvc\Router\RouteInterface */ - public function addPost($pattern, $paths = null); + public function addTrace(string $pattern, $paths = null): RouteInterface; /** - * Adds a route to the router that only match if the HTTP method is PUT + * Sets a callback that is called if the route is matched. + * The developer can implement any arbitrary conditions here + * If the callback returns false the route is treated as not matched * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @param callable $beforeMatch + * @return GroupInterface */ - public function addPut($pattern, $paths = null); + public function beforeMatch($beforeMatch): GroupInterface; /** - * Adds a route to the router that only match if the HTTP method is PATCH + * Removes all the pre-defined routes + */ + public function clear(); + + /** + * Returns the 'before match' callback if any * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return callable */ - public function addPatch($pattern, $paths = null); + public function getBeforeMatch(); /** - * Adds a route to the router that only match if the HTTP method is DELETE + * Returns the hostname restriction * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addDelete($pattern, $paths = null); + public function getHostname(): string; /** - * Add a route to the router that only match if the HTTP method is OPTIONS + * Returns the common paths defined for this group * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return array|string */ - public function addOptions($pattern, $paths = null); + public function getPaths(); /** - * Adds a route to the router that only match if the HTTP method is HEAD + * Returns the common prefix for all the routes * - * @param string $pattern - * @param mixed $paths - * @return \Phalcon\Mvc\Router\RouteInterface + * @return string */ - public function addHead($pattern, $paths = null); + public function getPrefix(): string; /** - * Removes all the pre-defined routes + * Returns the routes added to the group + * + * @return array|\Phalcon\Mvc\Router\RouteInterface[] */ - public function clear(); + public function getRoutes(): array; + + /** + * Set a hostname restriction for all the routes in the group + * + * @param string $hostname + * @return GroupInterface + */ + public function setHostname(string $hostname): GroupInterface; + + /** + * Set common paths for all the routes in the group + * + * @param array $paths + * @return GroupInterface + */ + public function setPaths($paths): GroupInterface; + + /** + * Set a common uri prefix for all the routes in this group + * + * @param string $prefix + * @return GroupInterface + */ + public function setPrefix(string $prefix): GroupInterface; } diff --git a/src/Phalcon/mvc/router/Route.php b/src/Phalcon/mvc/router/Route.php index 8397b84f..5f86e634 100644 --- a/src/Phalcon/mvc/router/Route.php +++ b/src/Phalcon/mvc/router/Route.php @@ -10,40 +10,40 @@ class Route implements \Phalcon\Mvc\Router\RouteInterface { - protected $_pattern; + protected $beforeMatch; - protected $_compiledPattern; + protected $compiledPattern; - protected $_paths; + protected $converters; - protected $_methods; + protected $group; - protected $_hostname; + protected $hostname; - protected $_converters; + protected $id; - protected $_id; + protected $methods; - protected $_name; + protected $match; - protected $_beforeMatch; + protected $name; - protected $_match; + protected $paths; - protected $_group; + protected $pattern; - static protected $_uniqueId; + static protected $uniqueId = 0; @@ -56,137 +56,103 @@ public function getId() {} * @param mixed $paths * @param mixed $httpMethods */ - public function __construct($pattern, $paths = null, $httpMethods = null) {} + public function __construct(string $pattern, $paths = null, $httpMethods = null) {} /** - * Replaces placeholders from pattern returning a valid PCRE regular expression - * - * @param string $pattern - * @return string - */ - public function compilePattern($pattern) {} - - /** - * Set one or more HTTP methods that constraint the matching of the route - * - * - * $route->via("GET"); + * Sets a callback that is called if the route is matched. + * The developer can implement any arbitrary conditions here + * If the callback returns false the route is treated as not matched * - * $route->via( + * ```php + * $router->add( + * "/login", * [ - * "GET", - * "POST", + * "module" => "admin", + * "controller" => "session", * ] + * )->beforeMatch( + * function ($uri, $route) { + * // Check if the request was made with Ajax + * if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + * return false; + * } + * + * return true; + * } * ); - * + * ``` * - * @param mixed $httpMethods - * @return Route + * @param mixed $callback + * @return RouteInterface */ - public function via($httpMethods) {} + public function beforeMatch($callback): RouteInterface {} /** - * Extracts parameters from a string + * Replaces placeholders from pattern returning a valid PCRE regular expression * * @param string $pattern - * @return array|bool + * @return string */ - public function extractNamedParams($pattern) {} + public function compilePattern(string $pattern): string {} /** - * Reconfigure the route adding a new pattern and a set of paths + * {@inheritdoc} + * + * @param string $name + * @param mixed $converter + * @return RouteInterface + */ + public function convert(string $name, $converter): RouteInterface {} + + /** + * Extracts parameters from a string * * @param string $pattern - * @param mixed $paths + * @return array|bool */ - public function reConfigure($pattern, $paths = null) {} + public function extractNamedParams(string $pattern) {} /** - * Returns routePaths + * Returns the 'before match' callback if any * - * @param mixed $paths - * @return array + * @return callable */ - public static function getRoutePaths($paths = null) {} + public function getBeforeMatch() {} /** - * Returns the route's name + * Returns the route's compiled pattern * * @return string */ - public function getName() {} + public function getCompiledPattern(): string {} /** - * Sets the route's name - * - * - * $router->add( - * "/about", - * [ - * "controller" => "about", - * ] - * )->setName("about"); - * + * Returns the router converter * - * @param string $name - * @return Route + * @return array */ - public function setName($name) {} + public function getConverters(): array {} /** - * Sets a callback that is called if the route is matched. - * The developer can implement any arbitrary conditions here - * If the callback returns false the route is treated as not matched - * - * - * $router->add( - * "/login", - * [ - * "module" => "admin", - * "controller" => "session", - * ] - * )->beforeMatch( - * function ($uri, $route) { - * // Check if the request was made with Ajax - * if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { - * return false; - * } - * - * return true; - * } - * ); - * + * Returns the group associated with the route * - * @param mixed $callback - * @return Route + * @return null|GroupInterface */ - public function beforeMatch($callback) {} + public function getGroup(): ?GroupInterface {} /** - * Returns the 'before match' callback if any + * Returns the HTTP methods that constraint matching the route * - * @return callable + * @return array|string */ - public function getBeforeMatch() {} + public function getHttpMethods() {} /** - * Allows to set a callback to handle the request directly in the route - * - * - * $router->add( - * "/help", - * [] - * )->match( - * function () { - * return $this->getResponse()->redirect("https://support.google.com/", true); - * } - * ); - * + * Returns the hostname restriction if any * - * @param mixed $callback - * @return Route + * @return string */ - public function match($callback) {} + public function getHostname(): string {} /** * Returns the 'match' callback if any @@ -196,137 +162,153 @@ public function match($callback) {} public function getMatch() {} /** - * Returns the route's id + * Returns the route's name * * @return string */ - public function getRouteId() {} + public function getName(): string {} /** - * Returns the route's pattern + * Returns the paths * - * @return string + * @return array */ - public function getPattern() {} + public function getPaths(): array {} /** - * Returns the route's compiled pattern + * Returns the route's pattern * * @return string */ - public function getCompiledPattern() {} - - /** - * Returns the paths - * - * @return array - */ - public function getPaths() {} + public function getPattern(): string {} /** * Returns the paths using positions as keys and names as values * * @return array */ - public function getReversedPaths() {} + public function getReversedPaths(): array {} /** - * Sets a set of HTTP methods that constraint the matching of the route (alias of via) - * - * - * $route->setHttpMethods("GET"); - * $route->setHttpMethods(["GET", "POST"]); - * + * Returns the route's id * - * @param mixed $httpMethods - * @return RouteInterface + * @return string */ - public function setHttpMethods($httpMethods) {} + public function getRouteId(): string {} /** - * Returns the HTTP methods that constraint matching the route + * Returns routePaths * - * @return array|string + * @param mixed $paths + * @return array */ - public function getHttpMethods() {} + public static function getRoutePaths($paths = null): array {} /** - * Sets a hostname restriction to the route + * Allows to set a callback to handle the request directly in the route * - * - * $route->setHostname("localhost"); - * + * ```php + * $router->add( + * "/help", + * [] + * )->match( + * function () { + * return $this->getResponse()->redirect("https://support.google.com/", true); + * } + * ); + * ``` * - * @param string $hostname + * @param mixed $callback * @return RouteInterface */ - public function setHostname($hostname) {} + public function match($callback): RouteInterface {} /** - * Returns the hostname restriction if any + * Reconfigure the route adding a new pattern and a set of paths * - * @return string + * @param string $pattern + * @param mixed $paths */ - public function getHostname() {} + public function reConfigure(string $pattern, $paths = null) {} + + /** + * Resets the internal route id generator + */ + public static function reset() {} /** * Sets the group associated with the route * * @param GroupInterface $group - * @return Route + * @return RouteInterface */ - public function setGroup(GroupInterface $group) {} + public function setGroup(GroupInterface $group): RouteInterface {} /** - * Returns the group associated with the route + * Sets a set of HTTP methods that constraint the matching of the route (alias of via) * - * @return null|GroupInterface + * ```php + * $route->setHttpMethods("GET"); + * + * $route->setHttpMethods( + * [ + * "GET", + * "POST", + * ] + * ); + * ``` + * + * @param mixed $httpMethods + * @return RouteInterface */ - public function getGroup() {} + public function setHttpMethods($httpMethods): RouteInterface {} /** - * Adds a converter to perform an additional transformation for certain parameter - * - * - * $router = new Phalcon\Mvc\Router(false); //create Router without default routes - * $route = $router->add("/catalog/([a-zA-Z0-9\_\-]+)/([^\?]+)", [ - * "controller" => "catalog", - * "action" => "show", - * "name" => 1, - * "params_" => 2, - * ]); - * - * //additional parsing - * $route->convert( - * 'params_', - * function ($string) { - * $array = explode('/', $string); - * array_walk($array, function (&$string) { - * $string = explode('-', $string); - * }); - * - * return $array; - * }); - * $router->handle("https://site.com/controller_name/param1-val1-val2/param2-val3"); - * //result is: `["params_"] = [["param1","val1","val2"], ["param2","val3"]]` - * + * Sets a hostname restriction to the route * - * @param string $name - * @param mixed $converter - * @return Route + * ```php + * $route->setHostname("localhost"); + * ``` + * + * @param string $hostname + * @return RouteInterface */ - public function convert($name, $converter) {} + public function setHostname(string $hostname): RouteInterface {} /** - * Returns the router converter + * Sets the route's name * - * @return array + * ```php + * $router->add( + * "/about", + * [ + * "controller" => "about", + * ] + * )->setName("about"); + * ``` + * + * @param string $name + * @return RouteInterface */ - public function getConverters() {} + public function setName(string $name): RouteInterface {} /** - * Resets the internal route id generator + * Set one or more HTTP methods that constraint the matching of the route + * + * ```php + * $route->via("GET"); + * + * $route->via( + * [ + * "GET", + * "POST", + * ] + * ); + * ``` + * + * @param mixed $httpMethods + * @return RouteInterface */ - public static function reset() {} + public function via($httpMethods): RouteInterface {} } diff --git a/src/Phalcon/mvc/router/RouteInterface.php b/src/Phalcon/mvc/router/RouteInterface.php index f6f1f632..77877799 100644 --- a/src/Phalcon/mvc/router/RouteInterface.php +++ b/src/Phalcon/mvc/router/RouteInterface.php @@ -11,110 +11,119 @@ interface RouteInterface { /** - * Sets a hostname restriction to the route + * Replaces placeholders from pattern returning a valid PCRE regular expression * - * @param string $hostname - * @return RouteInterface + * @param string $pattern + * @return string */ - public function setHostname($hostname); + public function compilePattern(string $pattern): string; /** - * Returns the hostname restriction if any + * Adds a converter to perform an additional transformation for certain parameter. * - * @return string + * @param string $name + * @param mixed $converter + * @return RouteInterface */ - public function getHostname(); + public function convert(string $name, $converter): RouteInterface; /** - * Replaces placeholders from pattern returning a valid PCRE regular expression + * Returns the route's pattern * - * @param string $pattern * @return string */ - public function compilePattern($pattern); + public function getCompiledPattern(): string; /** - * Set one or more HTTP methods that constraint the matching of the route + * Returns the hostname restriction if any * - * @param mixed $httpMethods + * @return string */ - public function via($httpMethods); + public function getHostname(): string; /** - * Reconfigure the route adding a new pattern and a set of paths + * Returns the HTTP methods that constraint matching the route * - * @param string $pattern - * @param mixed $paths + * @return string|array */ - public function reConfigure($pattern, $paths = null); + public function getHttpMethods(); /** * Returns the route's name * * @return string */ - public function getName(); + public function getName(): string; /** - * Sets the route's name + * Returns the paths * - * @param string $name + * @return array */ - public function setName($name); + public function getPaths(): array; /** - * Sets a set of HTTP methods that constraint the matching of the route + * Returns the route's pattern * - * @param mixed $httpMethods - * @return RouteInterface + * @return string */ - public function setHttpMethods($httpMethods); + public function getPattern(): string; /** - * Returns the route's id + * Returns the paths using positions as keys and names as values * - * @return string + * @return array */ - public function getRouteId(); + public function getReversedPaths(): array; /** - * Returns the route's pattern + * Returns the route's id * * @return string */ - public function getPattern(); + public function getRouteId(): string; /** - * Returns the route's pattern + * Sets a hostname restriction to the route * - * @return string + * @param string $hostname + * @return RouteInterface */ - public function getCompiledPattern(); + public function setHostname(string $hostname): RouteInterface; /** - * Returns the paths + * Sets a set of HTTP methods that constraint the matching of the route * - * @return array + * @param mixed $httpMethods + * @return RouteInterface */ - public function getPaths(); + public function setHttpMethods($httpMethods): RouteInterface; /** - * Returns the paths using positions as keys and names as values + * Sets the route's name * - * @return array + * @param string $name */ - public function getReversedPaths(); + public function setName(string $name); /** - * Returns the HTTP methods that constraint matching the route + * Reconfigure the route adding a new pattern and a set of paths * - * @return string|array + * @param string $pattern + * @param mixed $paths */ - public function getHttpMethods(); + public function reConfigure(string $pattern, $paths = null); /** * Resets the internal route id generator */ public static function reset(); + /** + * Set one or more HTTP methods that constraint the matching of the route + * + * @param mixed $httpMethods + */ + public function via($httpMethods); + } diff --git a/src/Phalcon/mvc/url/Exception.php b/src/Phalcon/mvc/url/Exception.php deleted file mode 100644 index f10048ee..00000000 --- a/src/Phalcon/mvc/url/Exception.php +++ /dev/null @@ -1,13 +0,0 @@ - + * ```php * use Phalcon\Mvc\View\Simple as View; * * $view = new View(); @@ -27,49 +27,43 @@ * "parameter" => $here, * ] * ); - * + * ``` */ class Simple extends \Phalcon\Di\Injectable implements \Phalcon\Mvc\ViewBaseInterface { - protected $_options; + protected $activeRenderPath; - protected $_viewsDir; - - - protected $_partialsDir; - - - protected $_viewParams; + protected $content; /** * @var \Phalcon\Mvc\View\EngineInterface[]|false */ - protected $_engines = false; + protected $engines = false; - /** - * @var array|null - */ - protected $_registeredEngines; + protected $options; - protected $_activeRenderPath; + protected $partialsDir; - protected $_content; + /** + * @var array|null + */ + protected $registeredEngines; - protected $_cache = false; + protected $viewsDir; - protected $_cacheOptions; + protected $viewParams = array(); /** * @return array|null */ - public function getRegisteredEngines() {} + public function getRegisteredEngines(): ?array {} /** * Phalcon\Mvc\View\Simple constructor @@ -79,69 +73,74 @@ public function getRegisteredEngines() {} public function __construct(array $options = array()) {} /** - * Sets views directory. Depending of your platform, always add a trailing slash or backslash + * Magic method to retrieve a variable passed to the view * - * @param string $viewsDir + * ```php + * echo $this->view->products; + * ``` + * + * @param string $key + * @return mixed|null */ - public function setViewsDir($viewsDir) {} + public function __get(string $key): ? {} /** - * Gets views directory + * Magic method to pass variables to the views * - * @return string + * ```php + * $this->view->products = $products; + * ``` + * + * @param string $key + * @param mixed $value */ - public function getViewsDir() {} + public function __set(string $key, $value) {} /** - * Register templating engines + * Returns the path of the view that is currently rendered * - * - * $this->view->registerEngines( - * [ - * ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", - * ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", - * ".mhtml" => "MyCustomEngine", - * ] - * ); - * + * @return string + */ + public function getActiveRenderPath(): string {} + + /** + * Returns output from another view stage * - * @param array $engines + * @return string */ - public function registerEngines(array $engines) {} + public function getContent(): string {} /** - * Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php + * Returns parameters to views * * @return array */ - protected function _loadTemplateEngines() {} + public function getParamsToView(): array {} /** - * Tries to render the view with every engine registered in the component + * Returns a parameter previously set in the view * - * @param string $path - * @param array $params + * @param string $key + * @return mixed|null */ - protected final function _internalRender($path, $params) {} + public function getVar(string $key): ? {} /** - * Renders a view + * Gets views directory * - * @param string $path - * @param array $params * @return string */ - public function render($path, $params = null) {} + public function getViewsDir(): string {} /** * Renders a partial view * - * + * ```php * // Show a partial inside another view * $this->partial("shared/footer"); - * + * ``` * - * + * ```php * // Show a partial inside another view with parameters * $this->partial( * "shared/footer", @@ -149,165 +148,115 @@ public function render($path, $params = null) {} * "content" => $html, * ] * ); - * + * ``` * * @param string $partialPath * @param mixed $params */ - public function partial($partialPath, $params = null) {} + public function partial(string $partialPath, $params = null) {} /** - * Sets the cache options + * Register templating engines * - * @param array $options - * @return Simple - */ - public function setCacheOptions(array $options) {} - - /** - * Returns the cache options + * ```php + * $this->view->registerEngines( + * [ + * ".phtml" => \Phalcon\Mvc\View\Engine\Php::class, + * ".volt" => \Phalcon\Mvc\View\Engine\Volt::class, + * ".mhtml" => \MyCustomEngine::class, + * ] + * ); + * ``` * - * @return array + * @param array $engines */ - public function getCacheOptions() {} + public function registerEngines(array $engines) {} /** - * Create a Phalcon\Cache based on the internal cache options + * Renders a view * - * @return \Phalcon\Cache\BackendInterface + * @param string $path + * @param array $params + * @return string */ - protected function _createCache() {} + public function render(string $path, array $params = array()): string {} /** - * Returns the cache instance used to cache + * Externally sets the view content + * + * ```php + * $this->view->setContent("

hello

"); + * ``` * - * @return \Phalcon\Cache\BackendInterface + * @param string $content + * @return Simple */ - public function getCache() {} + public function setContent(string $content): Simple {} /** - * Cache the actual view render to certain level + * Adds parameters to views (alias of setVar) * - * - * $this->view->cache( - * [ - * "key" => "my-key", - * "lifetime" => 86400, - * ] - * ); - * + * ```php + * $this->view->setParamToView("products", $products); + * ``` * - * @param mixed $options + * @param string $key + * @param mixed $value * @return Simple */ - public function cache($options = true) {} + public function setParamToView(string $key, $value): Simple {} /** - * Adds parameters to views (alias of setVar) + * Set a single view parameter * - * - * $this->view->setParamToView("products", $products); - * + * ```php + * $this->view->setVar("products", $products); + * ``` * * @param string $key * @param mixed $value * @return Simple */ - public function setParamToView($key, $value) {} + public function setVar(string $key, $value): Simple {} /** * Set all the render params * - * + * ```php * $this->view->setVars( * [ * "products" => $products, * ] * ); - * + * ``` * * @param array $params * @param bool $merge * @return Simple */ - public function setVars(array $params, $merge = true) {} + public function setVars(array $params, bool $merge = true): Simple {} /** - * Set a single view parameter - * - * - * $this->view->setVar("products", $products); - * + * Sets views directory * - * @param string $key - * @param mixed $value - * @return Simple - */ - public function setVar($key, $value) {} - - /** - * Returns a parameter previously set in the view - * - * @param string $key - * @return mixed|null + * @param string $viewsDir */ - public function getVar($key) {} + public function setViewsDir(string $viewsDir) {} /** - * Returns parameters to views + * Loads registered template engines, if none are registered it will use + * Phalcon\Mvc\View\Engine\Php * * @return array */ - public function getParamsToView() {} - - /** - * Externally sets the view content - * - * - * $this->view->setContent("

hello

"); - *
- * - * @param string $content - * @return Simple - */ - public function setContent($content) {} + protected function loadTemplateEngines(): array {} /** - * Returns cached output from another view stage - * - * @return string - */ - public function getContent() {} - - /** - * Returns the path of the view that is currently rendered - * - * @return string - */ - public function getActiveRenderPath() {} - - /** - * Magic method to pass variables to the views - * - * - * $this->view->products = $products; - * - * - * @param string $key - * @param mixed $value - */ - public function __set($key, $value) {} - - /** - * Magic method to retrieve a variable passed to the view - * - * - * echo $this->view->products; - * + * Tries to render the view with every engine registered in the component * - * @param string $key - * @return mixed|null + * @param string $path + * @param array $params */ - public function __get($key) {} + final protected function internalRender(string $path, $params) {} } diff --git a/src/Phalcon/mvc/view/Engine.php b/src/Phalcon/mvc/view/engine/AbstractEngine.php similarity index 62% rename from src/Phalcon/mvc/view/Engine.php rename to src/Phalcon/mvc/view/engine/AbstractEngine.php index 9ccfadcb..786bf49e 100644 --- a/src/Phalcon/mvc/view/Engine.php +++ b/src/Phalcon/mvc/view/engine/AbstractEngine.php @@ -1,48 +1,46 @@ + * ```php * $compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler(); * * $compiler->compile("views/partials/header.volt"); * * require $compiler->getCompiledTemplatePath(); - * + * ``` */ class Compiler implements \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; - - - protected $_view; + protected $autoescape = false; - protected $_options; + protected $blockLevel = 0; - protected $_arrayHelpers; + protected $blocks; - protected $_level = 0; + protected $container; - protected $_foreachLevel = 0; + protected $compiledTemplatePath; - protected $_blockLevel = 0; + protected $currentBlock; - protected $_exprLevel = 0; + protected $currentPath; - protected $_extended = false; + protected $exprLevel = 0; - protected $_autoescape = false; + protected $extended = false; - protected $_extendedBlocks; + protected $extensions; - protected $_currentBlock; + protected $extendedBlocks; - protected $_blocks; + protected $filters; - protected $_forElsePointers; + protected $foreachLevel = 0; - protected $_loopPointers; + protected $forElsePointers; - protected $_extensions; + protected $functions; - protected $_functions; + protected $level = 0; - protected $_filters; + protected $loopPointers; - protected $_macros; + protected $macros; - protected $_prefix; + protected $options; - protected $_currentPath; + protected $prefix; - protected $_compiledTemplatePath; + protected $view; /** @@ -92,194 +87,200 @@ class Compiler implements \Phalcon\Di\InjectionAwareInterface public function __construct(\Phalcon\Mvc\ViewBaseInterface $view = null) {} /** - * Sets the dependency injector - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the internal dependency injector + * Registers a Volt's extension * - * @return \Phalcon\DiInterface + * @param mixed $extension + * @return Compiler */ - public function getDI() {} + public function addExtension($extension): Compiler {} /** - * Sets the compiler options + * Register a new filter in the compiler * - * @param array $options + * @param string $name + * @param mixed $definition + * @return Compiler */ - public function setOptions(array $options) {} + public function addFilter(string $name, $definition): Compiler {} /** - * Sets a single compiler option + * Register a new function in the compiler * - * @param string $option - * @param mixed $value + * @param string $name + * @param mixed $definition + * @return Compiler */ - public function setOption($option, $value) {} + public function addFunction(string $name, $definition): Compiler {} /** - * Returns a compiler's option + * Resolves attribute reading * - * @param string $option + * @param array $expr * @return string */ - public function getOption($option) {} + public function attributeReader(array $expr): string {} /** - * Returns the compiler options + * Compiles a template into a file applying the compiler options + * This method does not return the compiled path if the template was not compiled * - * @return array - */ - public function getOptions() {} - - /** - * Fires an event to registered extensions + * ```php + * $compiler->compile("views/layouts/main.volt"); * - * @param string $name - * @param array $arguments - * @return mixed - */ - public final function fireExtensionEvent($name, $arguments = null) {} - - /** - * Registers a Volt's extension + * require $compiler->getCompiledTemplatePath(); + * ``` * - * @param mixed $extension - * @return Compiler + * @param string $templatePath + * @param bool $extendsMode */ - public function addExtension($extension) {} + public function compile(string $templatePath, bool $extendsMode = false) {} /** - * Returns the list of extensions registered in Volt + * Compiles a "autoescape" statement returning PHP code * - * @return array + * @param array $statement + * @param bool $extendsMode + * @return string */ - public function getExtensions() {} + public function compileAutoEscape(array $statement, bool $extendsMode): string {} /** - * Register a new function in the compiler + * Compiles a "cache" statement returning PHP code * - * @param string $name - * @param mixed $definition - * @return Compiler + * @param array $statement + * @param bool $extendsMode + * @return string */ - public function addFunction($name, $definition) {} + public function compileCache(array $statement, bool $extendsMode = false): string {} /** - * Register the user registered functions + * Compiles calls to macros * - * @return array + * @param array $statement + * @param bool $extendsMode */ - public function getFunctions() {} + public function compileCall(array $statement, bool $extendsMode) {} /** - * Register a new filter in the compiler + * Compiles a "case"/"default" clause returning PHP code * - * @param string $name - * @param mixed $definition - * @return Compiler + * @param array $statement + * @param bool $caseClause + * @return string */ - public function addFilter($name, $definition) {} + public function compileCase(array $statement, bool $caseClause = true): string {} /** - * Register the user registered filters + * Compiles a "do" statement returning PHP code * - * @return array + * @param array $statement + * @return string */ - public function getFilters() {} + public function compileDo(array $statement): string {} /** - * Set a unique prefix to be used as prefix for compiled variables + * Compiles a {% raw %}`{{` `}}`{% endraw %} statement returning PHP code * - * @param string $prefix - * @return Compiler + * @param array $statement + * @return string */ - public function setUniquePrefix($prefix) {} + public function compileEcho(array $statement): string {} /** - * Return a unique prefix to be used as prefix for compiled variables and contexts + * Compiles a "elseif" statement returning PHP code * + * @param array $statement * @return string */ - public function getUniquePrefix() {} + public function compileElseIf(array $statement): string {} /** - * Resolves attribute reading + * Compiles a template into a file forcing the destination path * - * @param array $expr - * @return string + * ```php + * $compiler->compileFile( + * "views/layouts/main.volt", + * "views/layouts/main.volt.php" + * ); + * ``` + * + * @param string $path + * @param string $compiledPath + * @param bool $extendsMode + * @return string|array */ - public function attributeReader(array $expr) {} + public function compileFile(string $path, string $compiledPath, bool $extendsMode = false) {} /** - * Resolves function intermediate code into PHP function calls + * Compiles a "foreach" intermediate code representation into plain PHP code * - * @param array $expr + * @param array $statement + * @param bool $extendsMode * @return string */ - public function functionCall(array $expr) {} + public function compileForeach(array $statement, bool $extendsMode = false): string {} /** - * Resolves filter intermediate code into a valid PHP expression + * Generates a 'forelse' PHP code * - * @param array $test - * @param string $left * @return string */ - public function resolveTest(array $test, $left) {} + public function compileForElse(): string {} /** - * Resolves filter intermediate code into PHP function calls + * Compiles a 'if' statement returning PHP code * - * @param array $filter - * @param string $left + * @param array $statement + * @param bool $extendsMode * @return string */ - final protected function resolveFilter(array $filter, $left) {} + public function compileIf(array $statement, bool $extendsMode = false): string {} /** - * Resolves an expression node in an AST volt tree + * Compiles a 'include' statement returning PHP code * - * @param array $expr + * @param array $statement * @return string */ - final public function expression(array $expr) {} + public function compileInclude(array $statement): string {} /** - * Compiles a block of statements + * Compiles macros * - * @param array $statements - * @return string|array + * @param array $statement + * @param bool $extendsMode + * @return string */ - final protected function _statementListOrExtends($statements) {} + public function compileMacro(array $statement, bool $extendsMode): string {} /** - * Compiles a "foreach" intermediate code representation into plain PHP code + * Compiles a "return" statement returning PHP code * * @param array $statement - * @param bool $extendsMode * @return string */ - public function compileForeach(array $statement, $extendsMode = false) {} + public function compileReturn(array $statement): string {} /** - * Generates a 'forelse' PHP code + * Compiles a "set" statement returning PHP code * + * @param array $statement * @return string */ - public function compileForElse() {} + public function compileSet(array $statement): string {} /** - * Compiles a 'if' statement returning PHP code + * Compiles a template into a string * - * @param array $statement + * ```php + * echo $compiler->compileString({% raw %}'{{ "hello world" }}'{% endraw %}); + * ``` + * + * @param string $viewCode * @param bool $extendsMode * @return string */ - public function compileIf(array $statement, $extendsMode = false) {} + public function compileString(string $viewCode, bool $extendsMode = false): string {} /** * Compiles a 'switch' statement returning PHP code @@ -288,195 +289,191 @@ public function compileIf(array $statement, $extendsMode = false) {} * @param bool $extendsMode * @return string */ - public function compileSwitch(array $statement, $extendsMode = false) {} + public function compileSwitch(array $statement, bool $extendsMode = false): string {} /** - * Compiles a "case"/"default" clause returning PHP code + * Resolves an expression node in an AST volt tree * - * @param array $statement - * @param bool $caseClause + * @param array $expr * @return string */ - public function compileCase(array $statement, $caseClause = true) {} + final public function expression(array $expr): string {} /** - * Compiles a "elseif" statement returning PHP code + * Fires an event to registered extensions * - * @param array $statement - * @return string + * @param string $name + * @param array $arguments + * @return mixed */ - public function compileElseIf(array $statement) {} + final public function fireExtensionEvent(string $name, $arguments = null) {} /** - * Compiles a "cache" statement returning PHP code + * Resolves function intermediate code into PHP function calls * - * @param array $statement - * @param bool $extendsMode + * @param array $expr * @return string */ - public function compileCache(array $statement, $extendsMode = false) {} + public function functionCall(array $expr): string {} /** - * Compiles a "set" statement returning PHP code + * Returns the path to the last compiled template * - * @param array $statement * @return string */ - public function compileSet(array $statement) {} + public function getCompiledTemplatePath(): string {} /** - * Compiles a "do" statement returning PHP code + * Returns the internal dependency injector * - * @param array $statement - * @return string + * @return \Phalcon\Di\DiInterface */ - public function compileDo(array $statement) {} + public function getDI(): DiInterface {} /** - * Compiles a "return" statement returning PHP code + * Returns the list of extensions registered in Volt * - * @param array $statement - * @return string + * @return array */ - public function compileReturn(array $statement) {} + public function getExtensions(): array {} /** - * Compiles a "autoescape" statement returning PHP code + * Register the user registered filters * - * @param array $statement - * @param bool $extendsMode - * @return string + * @return array */ - public function compileAutoEscape(array $statement, $extendsMode) {} + public function getFilters(): array {} /** - * Compiles a '{{' '}}' statement returning PHP code + * Register the user registered functions * - * @param array $statement - * @param boolean $extendsMode - * @return string + * @return array */ - public function compileEcho(array $statement) {} + public function getFunctions(): array {} /** - * Compiles a 'include' statement returning PHP code + * Returns a compiler's option * - * @param array $statement + * @param string $option * @return string */ - public function compileInclude(array $statement) {} + public function getOption(string $option) {} /** - * Compiles macros + * Returns the compiler options * - * @param array $statement - * @param bool $extendsMode - * @return string + * @return array */ - public function compileMacro(array $statement, $extendsMode) {} + public function getOptions(): array {} /** - * Compiles calls to macros + * Returns the path that is currently being compiled * - * @param array $statement - * @param boolean $extendsMode * @return string */ - public function compileCall(array $statement, $extendsMode) {} + public function getTemplatePath(): string {} /** - * Traverses a statement list compiling each of its nodes + * Return a unique prefix to be used as prefix for compiled variables and + * contexts * - * @param array $statements - * @param bool $extendsMode * @return string */ - final protected function _statementList(array $statements, $extendsMode = false) {} + public function getUniquePrefix(): string {} /** - * Compiles a Volt source code returning a PHP plain version + * Parses a Volt template returning its intermediate representation + * + * ```php + * print_r( + * $compiler->parse("{% raw %}{{ 3 + 2 }}{% endraw %}") + * ); + * ``` * * @param string $viewCode - * @param bool $extendsMode - * @return string + * @return array */ - protected function _compileSource($viewCode, $extendsMode = false) {} + public function parse(string $viewCode) {} /** - * Compiles a template into a string - * - * - * echo $compiler->compileString('{{ "hello world" }}'); - * + * Resolves filter intermediate code into a valid PHP expression * - * @param string $viewCode - * @param bool $extendsMode + * @param array $test + * @param string $left * @return string */ - public function compileString($viewCode, $extendsMode = false) {} + public function resolveTest(array $test, string $left): string {} /** - * Compiles a template into a file forcing the destination path + * Sets the dependency injector * - * - * $compiler->compileFile("views/layouts/main.volt", "views/layouts/main.volt.php"); - * + * @param \Phalcon\Di\DiInterface $container + */ + public function setDI(\Phalcon\Di\DiInterface $container) {} + + /** + * Sets a single compiler option * - * @param string $path - * @param string $compiledPath - * @param boolean $extendsMode - * @return string|array + * @param string $option + * @param mixed $value */ - public function compileFile($path, $compiledPath, $extendsMode = false) {} + public function setOption(string $option, $value) {} /** - * Compiles a template into a file applying the compiler options - * This method does not return the compiled path if the template was not compiled + * Sets the compiler options * - * - * $compiler->compile("views/layouts/main.volt"); + * @param array $options + */ + public function setOptions(array $options) {} + + /** + * Set a unique prefix to be used as prefix for compiled variables * - * require $compiler->getCompiledTemplatePath(); - * + * @param string $prefix + * @return Compiler + */ + public function setUniquePrefix(string $prefix): Compiler {} + + /** + * Compiles a Volt source code returning a PHP plain version * - * @param string $templatePath + * @param string $viewCode * @param bool $extendsMode + * @return string */ - public function compile($templatePath, $extendsMode = false) {} + protected function compileSource(string $viewCode, bool $extendsMode = false): string {} /** - * Returns the path that is currently being compiled + * Gets the final path with VIEW * - * @return string + * @param string $path */ - public function getTemplatePath() {} + protected function getFinalPath(string $path) {} /** - * Returns the path to the last compiled template + * Resolves filter intermediate code into PHP function calls * + * @param array $filter + * @param string $left * @return string */ - public function getCompiledTemplatePath() {} + final protected function resolveFilter(array $filter, string $left): string {} /** - * Parses a Volt template returning its intermediate representation - * - * - * print_r( - * $compiler->parse("{{ 3 + 2 }}") - * ); - * + * Traverses a statement list compiling each of its nodes * - * @param string $viewCode - * @return array + * @param array $statements + * @param bool $extendsMode + * @return string */ - public function parse($viewCode) {} + final protected function statementList(array $statements, bool $extendsMode = false): string {} /** - * Gets the final path with VIEW + * Compiles a block of statements * - * @param string $path + * @param array $statements + * @return string|array */ - protected function getFinalPath($path) {} + final protected function statementListOrExtends($statements) {} } diff --git a/src/Phalcon/mvc/view/engine/volt/Exception.php b/src/Phalcon/mvc/view/engine/volt/Exception.php index 0c9ec29b..8f230a7c 100644 --- a/src/Phalcon/mvc/view/engine/volt/Exception.php +++ b/src/Phalcon/mvc/view/engine/volt/Exception.php @@ -3,8 +3,6 @@ namespace Phalcon\Mvc\View\Engine\Volt; /** - * Phalcon\Mvc\View\Exception - * * Class for exceptions thrown by Phalcon\Mvc\View */ class Exception extends \Phalcon\Mvc\View\Exception @@ -19,13 +17,13 @@ class Exception extends \Phalcon\Mvc\View\Exception * @param int $code * @param \Exception $previous */ - public function __construct($message = '', array $statement = array(), $code = 0, \Exception $previous = null) {} + public function __construct(string $message = '', array $statement = array(), int $code = 0, \Exception $previous = null) {} /** * Gets currently parsed statement (if any). * * @return array */ - public function getStatement() {} + public function getStatement(): array {} } diff --git a/src/Phalcon/paginator/Adapter.php b/src/Phalcon/paginator/Adapter.php deleted file mode 100644 index 20238657..00000000 --- a/src/Phalcon/paginator/Adapter.php +++ /dev/null @@ -1,44 +0,0 @@ - - * use Phalcon\Paginator\Factory; - * $builder = $this->modelsManager->createBuilder() - * ->columns("id, name") - * ->from("Robots") - * ->orderBy("name"); - * - * $options = [ - * "builder" => $builder, - * "limit" => 20, - * "page" => 1, - * "adapter" => "queryBuilder", - * ]; - * $paginator = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - -} diff --git a/src/Phalcon/paginator/PaginatorFactory.php b/src/Phalcon/paginator/PaginatorFactory.php new file mode 100644 index 00000000..1b6a8f76 --- /dev/null +++ b/src/Phalcon/paginator/PaginatorFactory.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class PaginatorFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * AdapterFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Factory to create an instace from a Config object + * + * ```php + * use Phalcon\Paginator\PaginatorFactory; + * + * $builder = $this + * ->modelsManager + * ->createBuilder() + * ->columns("id, name") + * ->from(Robots::class) + * ->orderBy("name"); + * + * $options = [ + * "builder" => $builder, + * "limit" => 20, + * "page" => 1, + * "adapter" => "queryBuilder", + * ]; + * + * $paginator = (new PaginatorFactory())->load($options); + * ``` + * + * @param mixed $config + * @return mixed + */ + public function load($config) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @param array $options + * @return \Phalcon\Paginator\Adapter\AbstractAdapter + */ + public function newInstance(string $name, array $options = array()): AbstractAdapter {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/paginator/Repository.php b/src/Phalcon/paginator/Repository.php index 03fc7b1c..1d5fe849 100644 --- a/src/Phalcon/paginator/Repository.php +++ b/src/Phalcon/paginator/Repository.php @@ -5,106 +5,123 @@ /** * Phalcon\Paginator\Repository * - * Repository of current state Phalcon\Paginator\AdapterInterface::getPaginate() + * Repository of current state Phalcon\Paginator\AdapterInterface::paginate() */ -class Repository implements RepositoryInterface +class Repository implements \Phalcon\Paginator\RepositoryInterface { - protected $_properties = []; - protected $_aliases = []; - - /** - * {@inheritdoc} - */ - public function setProperties(array $properties) : RepositoryInterface - { - } - - /** - * {@inheritdoc} - */ - public function setAliases(array $aliases) : RepositoryInterface - { - } - - /** - * {@inheritdoc} - */ - public function getAliases() : array - { - } - - /** - * {@inheritdoc} - */ - public function getItems() { - } - - /** - * {@inheritdoc} - */ - public function getTotalItems() : int - { - } - - /** - * {@inheritdoc} - */ - public function getLimit() : int - { - } - - /** - * {@inheritdoc} - */ - public function getFirst() : int - { - } - - /** - * {@inheritdoc} - */ - public function getPrevious() : int - { - } - - /** - * {@inheritdoc} - */ - public function getCurrent() : int - { - } - - /** - * {@inheritdoc} - */ - public function getNext() : int - { - } - - /** - * {@inheritdoc} - */ - public function getLast() : int - { - } - - /** - * {@inheritdoc} - */ - public function __get(string $property) - { - } - - /** - * Gets value of property by name - */ - protected function getProperty(string $property, $defaultValue = null) { - } - - /** - * Resolve legacy alias for compatibility with version 2.0.x - */ - protected function getRealNameProperty(string $property) : string - { - } + /** + * @var array + */ + protected $aliases = array(); + + /** + * @var array + */ + protected $properties = array(); + + + /** + * {@inheritdoc} + * + * @param string $property + * @return mixed|null + */ + public function __get(string $property): ? {} + + /** + * {@inheritdoc} + * + * @return array + */ + public function getAliases(): array {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getCurrent(): int {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getFirst(): int {} + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getItems() {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getLast(): int {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getLimit(): int {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getNext(): int {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getPrevious(): int {} + + /** + * {@inheritdoc} + * + * @return int + */ + public function getTotalItems(): int {} + + /** + * {@inheritdoc} + * + * @param array $aliases + * @return RepositoryInterface + */ + public function setAliases(array $aliases): RepositoryInterface {} + + /** + * {@inheritdoc} + * + * @param array $properties + * @return RepositoryInterface + */ + public function setProperties(array $properties): RepositoryInterface {} + + /** + * Gets value of property by name + * + * @param string $property + * @param mixed $defaultValue + * @return mixed + */ + protected function getProperty(string $property, $defaultValue = null) {} + + /** + * Resolve alias property name + * + * @param string $property + * @return string + */ + protected function getRealNameProperty(string $property): string {} + } diff --git a/src/Phalcon/paginator/RepositoryInterface.php b/src/Phalcon/paginator/RepositoryInterface.php new file mode 100644 index 00000000..94b41503 --- /dev/null +++ b/src/Phalcon/paginator/RepositoryInterface.php @@ -0,0 +1,117 @@ + + * ```php * use Phalcon\Paginator\Adapter\Model; * * $paginator = new Model( @@ -18,37 +19,17 @@ * ] * ); * - * $paginate = $paginator->getPaginate(); - * + * $paginate = $paginator->paginate(); + * ``` */ -class Model extends \Phalcon\Paginator\Adapter +class Model extends \Phalcon\Paginator\Adapter\AbstractAdapter { - /** - * Configuration of paginator by model - */ - protected $_config = null; - - - /** - * Phalcon\Paginator\Adapter\Model constructor - * - * @param array $config - */ - public function __construct(array $config) {} - - /** - * Returns a slice of the resultset to show in the pagination - * - * @deprecated will be removed after 4.0 - * @return \stdClass - */ - public function getPaginate() {} /** * Returns a slice of the resultset to show in the pagination * - * @return \stdClass + * @return \Phalcon\Paginator\RepositoryInterface */ - public function paginate() {} + public function paginate(): RepositoryInterface {} } diff --git a/src/Phalcon/paginator/adapter/NativeArray.php b/src/Phalcon/paginator/adapter/NativeArray.php index 39fee906..36547901 100644 --- a/src/Phalcon/paginator/adapter/NativeArray.php +++ b/src/Phalcon/paginator/adapter/NativeArray.php @@ -7,7 +7,7 @@ * * Pagination using a PHP array as source of data * - * + * ```php * use Phalcon\Paginator\Adapter\NativeArray; * * $paginator = new NativeArray( @@ -23,36 +23,16 @@ * "page" => $currentPage, * ] * ); - * + * ``` */ -class NativeArray extends \Phalcon\Paginator\Adapter +class NativeArray extends \Phalcon\Paginator\Adapter\AbstractAdapter { - /** - * Configuration of the paginator - */ - protected $_config = null; - - - /** - * Phalcon\Paginator\Adapter\NativeArray constructor - * - * @param array $config - */ - public function __construct(array $config) {} - - /** - * Returns a slice of the resultset to show in the pagination - * - * @deprecated will be removed after 4.0 - * @return \stdClass - */ - public function getPaginate() {} /** * Returns a slice of the resultset to show in the pagination * - * @return \stdClass + * @return \Phalcon\Paginator\RepositoryInterface */ - public function paginate() {} + public function paginate(): RepositoryInterface {} } diff --git a/src/Phalcon/paginator/adapter/QueryBuilder.php b/src/Phalcon/paginator/adapter/QueryBuilder.php index ed229f0a..7e810c18 100644 --- a/src/Phalcon/paginator/adapter/QueryBuilder.php +++ b/src/Phalcon/paginator/adapter/QueryBuilder.php @@ -7,12 +7,12 @@ * * Pagination using a PHQL query builder as source of data * - * + * ```php * use Phalcon\Paginator\Adapter\QueryBuilder; * * $builder = $this->modelsManager->createBuilder() * ->columns("id, name") - * ->from("Robots") + * ->from(Robots::class) * ->orderBy("name"); * * $paginator = new QueryBuilder( @@ -22,24 +22,19 @@ * "page" => 1, * ] * ); - * + * ``` */ -class QueryBuilder extends \Phalcon\Paginator\Adapter +class QueryBuilder extends \Phalcon\Paginator\Adapter\AbstractAdapter { - /** - * Configuration of paginator by model - */ - protected $_config; - /** * Paginator's data */ - protected $_builder; + protected $builder; /** * Columns for count query if builder has having */ - protected $_columns; + protected $columns; /** @@ -54,36 +49,28 @@ public function __construct(array $config) {} * * @return int */ - public function getCurrentPage() {} - - /** - * Set query builder object - * - * @param \Phalcon\Mvc\Model\Query\Builder $builder - * @return QueryBuilder - */ - public function setQueryBuilder(\Phalcon\Mvc\Model\Query\Builder $builder) {} + public function getCurrentPage(): int {} /** * Get query builder object * * @return \Phalcon\Mvc\Model\Query\Builder */ - public function getQueryBuilder() {} + public function getQueryBuilder(): Builder {} /** * Returns a slice of the resultset to show in the pagination * - * @deprecated `will be removed after 4.0 - * @return \stdClass + * @return \Phalcon\Paginator\RepositoryInterface */ - public function getPaginate() {} + public function paginate(): RepositoryInterface {} /** - * Returns a slice of the resultset to show in the pagination + * Set query builder object * - * @return \stdClass + * @param \Phalcon\Mvc\Model\Query\Builder $builder + * @return QueryBuilder */ - public function paginate() {} + public function setQueryBuilder(\Phalcon\Mvc\Model\Query\Builder $builder): QueryBuilder {} } diff --git a/src/Phalcon/queue/Beanstalk.php b/src/Phalcon/queue/Beanstalk.php deleted file mode 100644 index fb1308ce..00000000 --- a/src/Phalcon/queue/Beanstalk.php +++ /dev/null @@ -1,269 +0,0 @@ - - * use Phalcon\Queue\Beanstalk; - * - * $queue = new Beanstalk( - * [ - * "host" => "127.0.0.1", - * "port" => 11300, - * "persistent" => true, - * ] - * ); - * - * - * @link http://www.igvita.com/2010/05/20/scalable-work-queues-with-beanstalk/ - */ -class Beanstalk -{ - /** - * Seconds to wait before putting the job in the ready queue. - * The job will be in the "delayed" state during this time. - * - * @const integer - */ - const DEFAULT_DELAY = 0; - - /** - * Jobs with smaller priority values will be scheduled before jobs with larger priorities. - * The most urgent priority is 0, the least urgent priority is 4294967295. - * - * @const integer - */ - const DEFAULT_PRIORITY = 100; - - /** - * Time to run - number of seconds to allow a worker to run this job. - * The minimum ttr is 1. - * - * @const integer - */ - const DEFAULT_TTR = 86400; - - /** - * Default tube name - * - * @const string - */ - const DEFAULT_TUBE = 'default'; - - /** - * Default connected host - * - * @const string - */ - const DEFAULT_HOST = '127.0.0.1'; - - /** - * Default connected port - * - * @const integer - */ - const DEFAULT_PORT = 11300; - - /** - * Connection resource - * - * @var resource - */ - protected $_connection; - - /** - * Connection options - * - * @var array - */ - protected $_parameters; - - - /** - * Phalcon\Queue\Beanstalk - * - * @param array $parameters - */ - public function __construct(array $parameters = array()) {} - - /** - * Makes a connection to the Beanstalkd server - * - * @return resource - */ - public function connect() {} - - /** - * Puts a job on the queue using specified tube. - * - * @param mixed $data - * @param array $options - * @return int|bool - */ - public function put($data, array $options = null) {} - - /** - * Reserves/locks a ready job from the specified tube. - * - * @param mixed $timeout - * @return bool|\Phalcon\Queue\Beanstalk\Job - */ - public function reserve($timeout = null) {} - - /** - * Change the active tube. By default the tube is "default". - * - * @param string $tube - * @return bool|string - */ - public function choose($tube) {} - - /** - * The watch command adds the named tube to the watch list for the current connection. - * - * @param string $tube - * @return bool|int - */ - public function watch($tube) {} - - /** - * It removes the named tube from the watch list for the current connection. - * - * @param string $tube - * @return bool|int - */ - public function ignore($tube) {} - - /** - * Can delay any new job being reserved for a given time. - * - * @param string $tube - * @param int $delay - * @return bool - */ - public function pauseTube($tube, $delay) {} - - /** - * The kick command applies only to the currently used tube. - * - * @param int $bound - * @return bool|int - */ - public function kick($bound) {} - - /** - * Gives statistical information about the system as a whole. - * - * @return bool|array - */ - public function stats() {} - - /** - * Gives statistical information about the specified tube if it exists. - * - * @param string $tube - * @return bool|array - */ - public function statsTube($tube) {} - - /** - * Returns a list of all existing tubes. - * - * @return bool|array - */ - public function listTubes() {} - - /** - * Returns the tube currently being used by the client. - * - * @return bool|string - */ - public function listTubeUsed() {} - - /** - * Returns a list tubes currently being watched by the client. - * - * @return bool|array - */ - public function listTubesWatched() {} - - /** - * Inspect the next ready job. - * - * @return bool|\Phalcon\Queue\Beanstalk\Job - */ - public function peekReady() {} - - /** - * Return the next job in the list of buried jobs. - * - * @return bool|\Phalcon\Queue\Beanstalk\Job - */ - public function peekBuried() {} - - /** - * Return the next job in the list of buried jobs. - * - * @return bool|\Phalcon\Queue\Beanstalk\Job - */ - public function peekDelayed() {} - - /** - * The peek commands let the client inspect a job in the system. - * - * @param int $id - * @return bool|\Phalcon\Queue\Beanstalk\Job - */ - public function jobPeek($id) {} - - /** - * Reads the latest status from the Beanstalkd server - * - * @return array - */ - final public function readStatus() {} - - /** - * Fetch a YAML payload from the Beanstalkd server - * - * @return array - */ - final public function readYaml() {} - - /** - * Reads a packet from the socket. Prior to reading from the socket will - * check for availability of the connection. - * - * @param int $length - * @return bool|string - */ - public function read($length = 0) {} - - /** - * Writes data to the socket. Performs a connection if none is available - * - * @param string $data - * @return bool|int - */ - public function write($data) {} - - /** - * Closes the connection to the beanstalk server. - * - * @return bool - */ - public function disconnect() {} - - /** - * Simply closes the connection. - * - * @return bool - */ - public function quit() {} - -} diff --git a/src/Phalcon/queue/beanstalk/Exception.php b/src/Phalcon/queue/beanstalk/Exception.php deleted file mode 100644 index e2bb63bc..00000000 --- a/src/Phalcon/queue/beanstalk/Exception.php +++ /dev/null @@ -1,13 +0,0 @@ - + * ```php * $random = new \Phalcon\Security\Random(); * * // Random binary string @@ -68,7 +68,7 @@ * echo $random->base58(); // Umjxqf7ZPwh765yR * echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 * echo $random->base58(7); // 774SJD3vgP - * + * ``` * * This class partially borrows SecureRandom library from Ruby * @@ -77,61 +77,21 @@ class Random { - /** - * Generates a random binary string - * - * The `Random::bytes` method returns a string and accepts as input an int - * representing the length in bytes to be returned. - * - * If $len is not specified, 16 is assumed. It may be larger in future. - * The result may contain any byte: "x00" - "xFF". - * - * - * $random = new \Phalcon\Security\Random(); - * - * $bytes = $random->bytes(); - * var_dump(bin2hex($bytes)); - * // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" - * - * - * @throws Exception If secure random number generator is not available or unexpected partial read - * @param int $len - * @return string - */ - public function bytes($len = 16) {} - - /** - * Generates a random hex string - * - * If $len is not specified, 16 is assumed. It may be larger in future. - * The length of the result string is usually greater of $len. - * - * - * $random = new \Phalcon\Security\Random(); - * - * echo $random->hex(10); // a29f470508d5ccb8e289 - * - * - * @throws Exception If secure random number generator is not available or unexpected partial read - * @param int $len - * @return string - */ - public function hex($len = null) {} - /** * Generates a random base58 string * * If $len is not specified, 16 is assumed. It may be larger in future. * The result may contain alphanumeric characters except 0, O, I and l. * - * It is similar to `Phalcon\Security\Random:base64` but has been modified to avoid both non-alphanumeric - * characters and letters which might look ambiguous when printed. + * It is similar to `Phalcon\Security\Random::base64()` but has been + * modified to avoid both non-alphanumeric characters and letters which + * might look ambiguous when printed. * - * + * ```php * $random = new \Phalcon\Security\Random(); * * echo $random->base58(); // 4kUgL2pdQMSCQtjE - * + * ``` * * @see \Phalcon\Security\Random:base64 * @link https://en.wikipedia.org/wiki/Base58 @@ -139,47 +99,49 @@ public function hex($len = null) {} * @param int $len * @return string */ - public function base58($len = null) {} + public function base58(int $len = null): string {} /** * Generates a random base62 string * * If $len is not specified, 16 is assumed. It may be larger in future. * - * It is similar to `Phalcon\Security\Random:base58` but has been modified to provide the largest value that can - * safely be used in URLs without needing to take extra characters into consideration because it is [A-Za-z0-9]. + * It is similar to `Phalcon\Security\Random::base58()` but has been + * modified to provide the largest value that can safely be used in URLs + * without needing to take extra characters into consideration because it is + * [A-Za-z0-9]. * - * + * ```php * $random = new \Phalcon\Security\Random(); * * echo $random->base62(); // z0RkwHfh8ErDM1xw - * + * ``` * * @see \Phalcon\Security\Random:base58 * @throws Exception If secure random number generator is not available or unexpected partial read * @param int $len * @return string */ - public function base62($len = null) {} + public function base62(int $len = null): string {} /** * Generates a random base64 string * * If $len is not specified, 16 is assumed. It may be larger in future. * The length of the result string is usually greater of $len. - * Size formula: 4 ($len / 3) and this need to be rounded up to a multiple of 4. + * Size formula: 4 ($len / 3) rounded up to a multiple of 4. * - * + * ```php * $random = new \Phalcon\Security\Random(); * * echo $random->base64(12); // 3rcq39QzGK9fUqh8 - * + * ``` * * @throws Exception If secure random number generator is not available or unexpected partial read * @param int $len * @return string */ - public function base64($len = null) {} + public function base64(int $len = null): string {} /** * Generates a random URL-safe base64 string @@ -187,15 +149,16 @@ public function base64($len = null) {} * If $len is not specified, 16 is assumed. It may be larger in future. * The length of the result string is usually greater of $len. * - * By default, padding is not generated because "=" may be used as a URL delimiter. - * The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. - * See RFC 3548 for the definition of URL-safe base64. + * By default, padding is not generated because "=" may be used as a URL + * delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also + * used if $padding is true. See RFC 3548 for the definition of URL-safe + * base64. * - * + * ```php * $random = new \Phalcon\Security\Random(); * * echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - * + * ``` * * @link https://www.ietf.org/rfc/rfc3548.txt * @throws Exception If secure random number generator is not available or unexpected partial read @@ -203,50 +166,94 @@ public function base64($len = null) {} * @param bool $padding * @return string */ - public function base64Safe($len = null, $padding = false) {} + public function base64Safe(int $len = null, bool $padding = false): string {} /** - * Generates a v4 random UUID (Universally Unique IDentifier) + * Generates a random binary string + * + * The `Random::bytes` method returns a string and accepts as input an int + * representing the length in bytes to be returned. + * + * If $len is not specified, 16 is assumed. It may be larger in future. + * The result may contain any byte: "x00" - "xFF". * - * The version 4 UUID is purely random (except the version). It doesn't contain meaningful - * information such as MAC address, time, etc. See RFC 4122 for details of UUID. + * ```php + * $random = new \Phalcon\Security\Random(); + * + * $bytes = $random->bytes(); + * var_dump(bin2hex($bytes)); + * // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + * ``` * - * This algorithm sets the version number (4 bits) as well as two reserved bits. - * All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. - * Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal - * digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). + * @throws Exception If secure random number generator is not available or unexpected partial read + * @param int $len + * @return string + */ + public function bytes(int $len = 16): string {} + + /** + * Generates a random hex string + * + * If $len is not specified, 16 is assumed. It may be larger in future. + * The length of the result string is usually greater of $len. * - * + * ```php * $random = new \Phalcon\Security\Random(); * - * echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 - * + * echo $random->hex(10); // a29f470508d5ccb8e289 + * ``` * - * @link https://www.ietf.org/rfc/rfc4122.txt * @throws Exception If secure random number generator is not available or unexpected partial read + * @param int $len * @return string */ - public function uuid() {} + public function hex(int $len = null): string {} /** * Generates a random number between 0 and $len * * Returns an integer: 0 <= result <= $len. * - * + * ```php * $random = new \Phalcon\Security\Random(); * * echo $random->number(16); // 8 - * + * ``` * * @throws Exception If secure random number generator is not available, unexpected partial read or $len <= 0 * @param int $len * @return int */ - public function number($len) {} + public function number(int $len): int {} + + /** + * Generates a v4 random UUID (Universally Unique IDentifier) + * + * The version 4 UUID is purely random (except the version). It doesn't + * contain meaningful information such as MAC address, time, etc. See RFC + * 4122 for details of UUID. + * + * This algorithm sets the version number (4 bits) as well as two reserved + * bits. All other bits (the remaining 122 bits) are set using a random or + * pseudorandom data source. Version 4 UUIDs have the form + * xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and + * y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). + * + * ```php + * $random = new \Phalcon\Security\Random(); + * + * echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + * ``` + * + * @link https://www.ietf.org/rfc/rfc4122.txt + * @throws Exception If secure random number generator is not available or unexpected partial read + * @return string + */ + public function uuid(): string {} /** - * Generates a random string based on the number ($base) of characters ($alphabet). + * Generates a random string based on the number ($base) of characters + * ($alphabet). * * If $n is not specified, 16 is assumed. It may be larger in future. * @@ -256,6 +263,6 @@ public function number($len) {} * @param mixed $n * @return string */ - protected function base($alphabet, $base, $n = null) {} + protected function base(string $alphabet, int $base, $n = null): string {} } diff --git a/src/Phalcon/service/Exception.php b/src/Phalcon/service/Exception.php deleted file mode 100644 index 22ac2332..00000000 --- a/src/Phalcon/service/Exception.php +++ /dev/null @@ -1,12 +0,0 @@ - - * $session->setOptions( - * [ - * "uniqueId" => "my-private-app", - * ] - * ); - * - * - * @param array $options - */ - public function setOptions(array $options) {} - - /** - * Get internal options - * - * @return array - */ - public function getOptions() {} - - /** - * Set session name - * - * @param string $name - */ - public function setName($name) {} - - /** - * Get session name - * - * @return string - */ - public function getName() {} - - /** - * {@inheritdoc} - * - * @param bool $deleteOldSession - * @return AdapterInterface - */ - public function regenerateId($deleteOldSession = true) {} - - /** - * Gets a session variable from an application context - * - * - * $session->get("auth", "yes"); - * - * - * @param string $index - * @param mixed $defaultValue - * @param bool $remove - * @return mixed - */ - public function get($index, $defaultValue = null, $remove = false) {} - - /** - * Sets a session variable in an application context - * - * - * $session->set("auth", "yes"); - * - * - * @param string $index - * @param mixed $value - */ - public function set($index, $value) {} - - /** - * Check whether a session variable is set in an application context - * - * - * var_dump( - * $session->has("auth") - * ); - * - * - * @param string $index - * @return bool - */ - public function has($index) {} - - /** - * Removes a session variable from an application context - * - * - * $session->remove("auth"); - * - * - * @param string $index - */ - public function remove($index) {} - - /** - * Returns active session id - * - * - * echo $session->getId(); - * - * - * @return string - */ - public function getId() {} - - /** - * Set the current session id - * - * - * $session->setId($id); - * - * - * @param string $id - */ - public function setId($id) {} - - /** - * Check whether the session has been started - * - * - * var_dump( - * $session->isStarted() - * ); - * - * - * @return bool - */ - public function isStarted() {} - - /** - * Destroys the active session - * - * - * var_dump( - * $session->destroy() - * ); - * - * var_dump( - * $session->destroy(true) - * ); - * - * - * @param mixed $removeData - * @return bool - */ - public function destroy($removeData = null) {} - - /** - * Returns the status of the current session. - * - * - * var_dump( - * $session->status() - * ); - * - * if ($session->status() !== $session::SESSION_ACTIVE) { - * $session->start(); - * } - * - * - * @return int - */ - public function status() {} - - /** - * Alias: Gets a session variable from an application context - * - * @param string $index - * @return mixed - */ - public function __get($index) {} - - /** - * Alias: Sets a session variable in an application context - * - * @param string $index - * @param mixed $value - */ - public function __set($index, $value) {} - - /** - * Alias: Check whether a session variable is set in an application context - * - * @param string $index - * @return bool - */ - public function __isset($index) {} - - /** - * Alias: Removes a session variable from an application context - * - * - * unset($session->auth); - * - * - * @param string $index - */ - public function __unset($index) {} - - - public function __destruct() {} - - - protected function removeSessionData() {} - -} diff --git a/src/Phalcon/session/AdapterInterface.php b/src/Phalcon/session/AdapterInterface.php deleted file mode 100644 index aba0f232..00000000 --- a/src/Phalcon/session/AdapterInterface.php +++ /dev/null @@ -1,108 +0,0 @@ - + * ```php * $user = new \Phalcon\Session\Bag("user"); * * $user->name = "Kimbra Johnson"; * $user->age = 22; - * + * ``` */ -class Bag implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Session\BagInterface, \IteratorAggregate, \ArrayAccess, \Countable +class Bag extends \Phalcon\Collection implements \Phalcon\Di\InjectionAwareInterface { - protected $_dependencyInjector; + private $container; - protected $_name = null; + private $name = null; - protected $_data; - - - protected $_initialized = false; - - - protected $_session; + private $session; /** @@ -38,176 +33,47 @@ class Bag implements \Phalcon\Di\InjectionAwareInterface, \Phalcon\Session\BagIn * * @param string $name */ - public function __construct($name) {} - - /** - * Sets the DependencyInjector container - * - * @param \Phalcon\DiInterface $dependencyInjector - */ - public function setDI(\Phalcon\DiInterface $dependencyInjector) {} - - /** - * Returns the DependencyInjector container - * - * @return \Phalcon\DiInterface - */ - public function getDI() {} - - /** - * Initializes the session bag. This method must not be called directly, the - * class calls it when its internal data is accessed - */ - public function initialize() {} + public function __construct(string $name) {} /** * Destroys the session bag - * - * - * $user->destroy(); - * - */ - public function destroy() {} - - /** - * Sets a value in the session bag - * - * - * $user->set("name", "Kimbra"); - * - * - * @param string $property - * @param mixed $value - */ - public function set($property, $value) {} - - /** - * Magic setter to assign values to the session bag - * - * - * $user->name = "Kimbra"; - * - * - * @param string $property - * @param mixed $value - */ - public function __set($property, $value) {} - - /** - * Obtains a value from the session bag optionally setting a default value - * - * - * echo $user->get("name", "Kimbra"); - * - * - * @param string $property - * @param mixed $defaultValue */ - public function get($property, $defaultValue = null) {} + public function clear() {} /** - * Magic getter to obtain values from the session bag - * - * - * echo $user->name; - * - * - * @param string $property - * @return mixed - */ - public function __get($property) {} - - /** - * Check whether a property is defined in the internal bag - * - * - * var_dump( - * $user->has("name") - * ); - * - * - * @param string $property - * @return bool - */ - public function has($property) {} - - /** - * Magic isset to check whether a property is defined in the bag - * - * - * var_dump( - * isset($user["name"]) - * ); - * + * Returns the DependencyInjector container * - * @param string $property - * @return bool + * @return \Phalcon\Di\DiInterface */ - public function __isset($property) {} + public function getDI(): DiInterface {} /** * Removes a property from the internal bag * - * - * $user->remove("name"); - * - * - * @param string $property - * @return bool - */ - public function remove($property) {} - - /** - * Magic unset to remove items using the array syntax - * - * - * unset($user["name"]); - * - * - * @param string $property - * @return bool + * @param array $data */ - public function __unset($property) {} + public function init(array $data = array()) {} /** - * Return length of bag - * - * - * echo $user->count(); - * + * Removes a property from the internal bag * - * @return int + * @param string $element */ - public final function count() {} + public function remove(string $element) {} /** - *  Returns the bag iterator + * Sets a value in the session bag * - * @return \ArrayIterator - */ - public final function getIterator() {} - - /** - * @param mixed $property + * @param string $element * @param mixed $value */ - public final function offsetSet($property, $value) {} + public function set(string $element, $value) {} /** - * @param mixed $property - * @return bool - */ - public final function offsetExists($property) {} - - /** - * @param mixed $property - */ - public final function offsetUnset($property) {} - - /** - * @param mixed $property - * @return mixed + * Sets the DependencyInjector container + * + * @param \Phalcon\Di\DiInterface $container */ - public final function offsetGet($property) {} + public function setDI(\Phalcon\Di\DiInterface $container) {} } diff --git a/src/Phalcon/session/BagInterface.php b/src/Phalcon/session/BagInterface.php deleted file mode 100644 index ed3afba4..00000000 --- a/src/Phalcon/session/BagInterface.php +++ /dev/null @@ -1,73 +0,0 @@ - - * use Phalcon\Session\Factory; - * - * $options = [ - * "uniqueId" => "my-private-app", - * "host" => "127.0.0.1", - * "port" => 11211, - * "persistent" => true, - * "lifetime" => 3600, - * "prefix" => "my_", - * "adapter" => "memcache", - * ]; - * $session = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - -} diff --git a/src/Phalcon/session/Manager.php b/src/Phalcon/session/Manager.php index 19b0c3b4..1ce22d22 100644 --- a/src/Phalcon/session/Manager.php +++ b/src/Phalcon/session/Manager.php @@ -2,238 +2,237 @@ namespace Phalcon\Session; -use InvalidArgumentException; -use RuntimeException; -use SessionHandlerInterface; -use Phalcon\DiInterface; -use Phalcon\DI\InjectionAwareInterface; -use Phalcon\Helper\Arr; -use Phalcon\Session\ManagerInterface; - /** * Phalcon\Session\Manager * * Session manager class */ -class Manager implements ManagerInterface, InjectionAwareInterface +class Manager implements \Phalcon\Session\ManagerInterface, \Phalcon\DI\InjectionAwareInterface { /** * @var */ private $container; - /** - * @var |null - */ - private $handler = null; - - /** - * @var string - */ - private $name = ""; - - /** - * @var array - */ - private $options = []; - - /** - * @var string - */ - private $uniqueId = ""; - - /** - * Manager constructor. - * - * @param array options - */ - public function __construct(array $options = []) - { - } - - - /** - * Alias: Gets a session variable from an application context - */ - public function __get(string $key) { - } - - /** - * Alias: Check whether a session variable is set in an application context - */ - public function __isset(string $key) : bool - { - } - - /** - * Alias: Sets a session variable in an application context - */ - public function __set(string $key, $value) : void - { - } - - /** - * Alias: Removes a session variable from an application context - */ - public function __unset(string $key) - { - } - - /** - * Destroy/end a session - */ - public function destroy() : void - { - } - - /** - * Check whether the session has been started - */ - public function exists() : bool - { - } - - /** - * Gets a session variable from an application context - */ - public function get(string $key, $defaultValue = null, bool $remove = false) { - } - - /** - * Returns the DependencyInjector container - */ - public function getDI() : DiInterface - { - } - - /** - * Returns the stored session handler - */ - public function getHandler() : SessionHandlerInterface - { - } - - /** - * Returns the session id - */ - public function getId() : string - { - } - - /** - * Returns the name of the session - */ - public function getName() : string - { - } - - /** - * Check whether a session variable is set in an application context - */ - public function has(string $key) : bool - { - } - - /** - * Get internal options - */ - public function getOptions() : array - { - } - - /** - * Regenerates the session id using the handler. - */ - public function regenerateId($deleteOldSession = true) : ManagerInterface - { - } - - /** - * Registers a handler with the session - */ - public function registerHandler(SessionHandlerInterface $handler) : bool - { - } - - /** - * Removes a session variable from an application context - */ - public function remove(string $key) - { - } - - /** - * Sets a session variable in an application context - */ - public function set(string $key, $value) : void - { - } - - /** - * Sets the DependencyInjector container - */ - public function setDI(DiInterface $container) - { - } - - /** - * Set the handler for the session - */ - public function setHandler(SessionHandlerInterface $handler) : ManagerInterface - { - } - - /** - * Set session Id - */ - public function setId(string $id) : ManagerInterface - { - } - - /** - * Set the session name. Throw exception if the session has started - * and do not allow poop names - * - * @param string name - * - * @throws InvalidArgumentException - * - * @return Manager - */ - public function setName(string $name) : ManagerInterface - { - } - - /** - * Sets session's options - * - * @param array options - */ - public function setOptions(array $options) : void - { - } - - /** - * Starts the session (if headers are already sent the session will not be - * started) - */ - public function start() : bool - { - } - - /** - * Returns the status of the current session. - * - * @return int - */ - public function status() : int - { - } - - /** - * Returns the key prefixed - */ - private function getUniqueKey(string $key) : string - { - } + /** + * @var |null + */ + private $handler = null; + + /** + * @var string + */ + private $name = ''; + + /** + * @var array + */ + private $options = array(); + + /** + * @var string + */ + private $uniqueId = ''; + + + /** + * Manager constructor. + * + * @param array $options + */ + public function __construct(array $options = array()) {} + + /** + * Alias: Gets a session variable from an application context + * + * @param string $key + * @return mixed + */ + public function __get(string $key) {} + + /** + * Alias: Check whether a session variable is set in an application context + * + * @param string $key + * @return bool + */ + public function __isset(string $key): bool {} + + /** + * Alias: Sets a session variable in an application context + * + * @param string $key + * @param mixed $value + */ + public function __set(string $key, $value) {} + + /** + * Alias: Removes a session variable from an application context + * + * @param string $key + */ + public function __unset(string $key) {} + + /** + * Destroy/end a session + */ + public function destroy() {} + + /** + * Check whether the session has been started + * + * @return bool + */ + public function exists(): bool {} + + /** + * Gets a session variable from an application context + * + * @param string $key + * @param mixed $defaultValue + * @param bool $remove + * @return mixed + */ + public function get(string $key, $defaultValue = null, bool $remove = false) {} + + /** + * Returns the DependencyInjector container + * + * @return \Phalcon\Di\DiInterface + */ + public function getDI(): DiInterface {} + + /** + * Returns the stored session handler + * + * @return \SessionHandlerInterface + */ + public function getHandler(): SessionHandlerInterface {} + + /** + * Returns the session id + * + * @return string + */ + public function getId(): string {} + + /** + * Returns the name of the session + * + * @return string + */ + public function getName(): string {} + + /** + * Check whether a session variable is set in an application context + * + * @param string $key + * @return bool + */ + public function has(string $key): bool {} + + /** + * Get internal options + * + * @return array + */ + public function getOptions(): array {} + + /** + * Regenerates the session id using the handler. + * + * @param mixed $deleteOldSession + * @return \Phalcon\Session\ManagerInterface + */ + public function regenerateId($deleteOldSession = true): ManagerInterface {} + + /** + * Registers a handler with the session + * + * @param \SessionHandlerInterface $handler + * @return bool + */ + public function registerHandler(\SessionHandlerInterface $handler): bool {} + + /** + * Removes a session variable from an application context + * + * @param string $key + */ + public function remove(string $key) {} + + /** + * Sets a session variable in an application context + * + * @param string $key + * @param mixed $value + */ + public function set(string $key, $value) {} + + /** + * Sets the DependencyInjector container + * + * @param \Phalcon\Di\DiInterface $container + */ + public function setDI(\Phalcon\Di\DiInterface $container) {} + + /** + * Set the handler for the session + * + * @param \SessionHandlerInterface $handler + * @return \Phalcon\Session\ManagerInterface + */ + public function setHandler(\SessionHandlerInterface $handler): ManagerInterface {} + + /** + * Set session Id + * + * @param string $id + * @return \Phalcon\Session\ManagerInterface + */ + public function setId(string $id): ManagerInterface {} + + /** + * Set the session name. Throw exception if the session has started + * and do not allow poop names + * + * @param string name + * + * @throws InvalidArgumentException + * + * @param string $name + * @return \Phalcon\Session\ManagerInterface + */ + public function setName(string $name): ManagerInterface {} + + /** + * Sets session's options + * + * @param array $options + */ + public function setOptions(array $options) {} + + /** + * Starts the session (if headers are already sent the session will not be + * started) + * + * @return bool + */ + public function start(): bool {} + + /** + * Returns the status of the current session. + * + * @return int + */ + public function status(): int {} + + /** + * Returns the key prefixed + * + * @param string $key + * @return string + */ + private function getUniqueKey(string $key): string {} + } diff --git a/src/Phalcon/session/ManagerInterface.php b/src/Phalcon/session/ManagerInterface.php new file mode 100644 index 00000000..0bdb4024 --- /dev/null +++ b/src/Phalcon/session/ManagerInterface.php @@ -0,0 +1,189 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +abstract class AbstractAdapter implements \SessionHandlerInterface +{ + /** + * @var + */ + protected $adapter; + + + /** + * Close + * + * @return bool + */ + public function close(): bool {} + + /** + * Destroy + * + * @param mixed $id + * @return bool + */ + public function destroy($id): bool {} + + /** + * Garbage Collector + * + * @param mixed $maxlifetime + * @return bool + */ + public function gc($maxlifetime): bool {} + + /** + * Read + * + * @param mixed $id + * @return string + */ + public function read($id): string {} + + /** + * Open + * + * @param mixed $savePath + * @param mixed $sessionName + * @return bool + */ + public function open($savePath, $sessionName): bool {} + + /** + * Write + * + * @param mixed $id + * @param mixed $data + * @return bool + */ + public function write($id, $data): bool {} + +} diff --git a/src/Phalcon/session/adapter/Files.php b/src/Phalcon/session/adapter/Files.php deleted file mode 100644 index ffe3b7f0..00000000 --- a/src/Phalcon/session/adapter/Files.php +++ /dev/null @@ -1,29 +0,0 @@ - - * use Phalcon\Session\Adapter\Files; - * - * $session = new Files( - * [ - * "uniqueId" => "my-private-app", - * ] - * ); - * - * $session->start(); - * - * $session->set("var", "some-value"); - * - * echo $session->get("var"); - * - */ -class Files extends \Phalcon\Session\Adapter -{ - -} diff --git a/src/Phalcon/session/adapter/Libmemcached.php b/src/Phalcon/session/adapter/Libmemcached.php index c1d60223..83668e14 100644 --- a/src/Phalcon/session/adapter/Libmemcached.php +++ b/src/Phalcon/session/adapter/Libmemcached.php @@ -4,100 +4,16 @@ /** * Phalcon\Session\Adapter\Libmemcached - * - * This adapter store sessions in libmemcached - * - * - * use Phalcon\Session\Adapter\Libmemcached; - * - * $session = new Libmemcached( - * [ - * "servers" => [ - * [ - * "host" => "localhost", - * "port" => 11211, - * "weight" => 1, - * ], - * ], - * "client" => [ - * \Memcached::OPT_HASH => \Memcached::HASH_MD5, - * \Memcached::OPT_PREFIX_KEY => "prefix.", - * ], - * "lifetime" => 3600, - * "prefix" => "my_", - * ] - * ); - * - * $session->start(); - * - * $session->set("var", "some-value"); - * - * echo $session->get("var"); - * */ -class Libmemcached extends \Phalcon\Session\Adapter +class Libmemcached extends \Phalcon\Session\Adapter\AbstractAdapter { - protected $_libmemcached = null; - - - protected $_lifetime = 8600; - - - - public function getLibmemcached() {} - - - public function getLifetime() {} - /** - * Phalcon\Session\Adapter\Libmemcached constructor + * Constructor * - * @throws \Phalcon\Session\Exception + * @param \Phalcon\Storage\AdapterFactory $factory * @param array $options */ - public function __construct(array $options) {} - - /** - * @return bool - */ - public function open() {} - - /** - * @return bool - */ - public function close() {} - - /** - * {@inheritdoc} - * - * @param string $sessionId - * @return string - */ - public function read($sessionId) {} - - /** - * {@inheritdoc} - * - * @param string $sessionId - * @param string $data - * @return bool - */ - public function write($sessionId, $data) {} - - /** - * {@inheritdoc} - * - * @param mixed $sessionId - * @return bool - */ - public function destroy($sessionId = null) {} - - /** - * {@inheritdoc} - * - * @return bool - */ - public function gc() {} + public function __construct(\Phalcon\Storage\AdapterFactory $factory, array $options = array()) {} } diff --git a/src/Phalcon/session/adapter/Memcache.php b/src/Phalcon/session/adapter/Memcache.php deleted file mode 100644 index c5cac728..00000000 --- a/src/Phalcon/session/adapter/Memcache.php +++ /dev/null @@ -1,95 +0,0 @@ - - * use Phalcon\Session\Adapter\Memcache; - * - * $session = new Memcache( - * [ - * "uniqueId" => "my-private-app", - * "host" => "127.0.0.1", - * "port" => 11211, - * "persistent" => true, - * "lifetime" => 3600, - * "prefix" => "my_", - * ] - * ); - * - * $session->start(); - * - * $session->set("var", "some-value"); - * - * echo $session->get("var"); - * - */ -class Memcache extends \Phalcon\Session\Adapter -{ - - protected $_memcache = null; - - - protected $_lifetime = 8600; - - - - public function getMemcache() {} - - - public function getLifetime() {} - - /** - * Phalcon\Session\Adapter\Memcache constructor - * - * @param array $options - */ - public function __construct(array $options = array()) {} - - /** - * @return bool - */ - public function open() {} - - /** - * @return bool - */ - public function close() {} - - /** - * {@inheritdoc} - * - * @param string $sessionId - * @return string - */ - public function read($sessionId) {} - - /** - * {@inheritdoc} - * - * @param string $sessionId - * @param string $data - * @return bool - */ - public function write($sessionId, $data) {} - - /** - * {@inheritdoc} - * - * @param mixed $sessionId - * @return bool - */ - public function destroy($sessionId = null) {} - - /** - * {@inheritdoc} - * - * @return bool - */ - public function gc() {} - -} diff --git a/src/Phalcon/session/adapter/Noop.php b/src/Phalcon/session/adapter/Noop.php index ed866229..02a62873 100644 --- a/src/Phalcon/session/adapter/Noop.php +++ b/src/Phalcon/session/adapter/Noop.php @@ -2,15 +2,13 @@ namespace Phalcon\Session\Adapter; -use SessionHandlerInterface; - /** * Phalcon\Session\Adapter\Noop * * This is an "empty" or null adapter. It can be used for testing or any * other purpose that no session needs to be invoked * - * + * ```php * setHandler(new Noop()); - * + * ``` */ -class Noop implements SessionHandlerInterface +class Noop implements \SessionHandlerInterface { /** * The connection of some adapters */ - protected $connection; + protected $connection; - /** - * Session options - * - * @var array - */ - protected $options = []; + /** + * Session options + * + * @var array + */ + protected $options = array(); - /** - * Session prefix - * - * @var string - */ - protected $prefix = ""; + /** + * Session prefix + * + * @var string + */ + protected $prefix = ''; - /** - * Time To Live - * - * @var int - */ - protected $ttl = 8600; + /** + * Time To Live + * + * @var int + */ + protected $ttl = 8600; - /** - * Constructor - */ - public function __construct(array $options = []) - { - } - /** - * Close - */ - public function close() : bool - { - } + /** + * Constructor + * + * @param array $options + */ + public function __construct(array $options = array()) {} - /** - * Destroy - */ - public function destroy($id) : bool - { - } + /** + * Close + * + * @return bool + */ + public function close(): bool {} - /** - * Garbage Collector - */ - public function gc($maxlifetime) : bool - { - } + /** + * Destroy + * + * @param mixed $id + * @return bool + */ + public function destroy($id): bool {} - /** - * Read - */ - public function read($id) : string - { - } + /** + * Garbage Collector + * + * @param mixed $maxlifetime + * @return bool + */ + public function gc($maxlifetime): bool {} + + /** + * Read + * + * @param mixed $id + * @return string + */ + public function read($id): string {} + + /** + * Open + * + * @param mixed $savePath + * @param mixed $sessionName + * @return bool + */ + public function open($savePath, $sessionName): bool {} - /** - * Open - */ - public function open($savePath, $sessionName) : bool - { - } + /** + * Write + * + * @param mixed $id + * @param mixed $data + * @return bool + */ + public function write($id, $data): bool {} - /** - * Write - */ - public function write($id, $data) : bool - { - } + /** + * Helper method to get the name prefixed + * + * @param mixed $name + * @return string + */ + protected function getPrefixedName($name): string {} - /** - * Helper method to get the name prefixed - */ - protected function getPrefixedName($name) : string - { - } } diff --git a/src/Phalcon/session/adapter/Redis.php b/src/Phalcon/session/adapter/Redis.php index 179e2d47..9df67fd7 100644 --- a/src/Phalcon/session/adapter/Redis.php +++ b/src/Phalcon/session/adapter/Redis.php @@ -4,98 +4,16 @@ /** * Phalcon\Session\Adapter\Redis - * - * This adapter store sessions in Redis - * - * - * use Phalcon\Session\Adapter\Redis; - * - * $session = new Redis( - * [ - * "uniqueId" => "my-private-app", - * "host" => "localhost", - * "port" => 6379, - * "auth" => "foobared", - * "persistent" => false, - * "lifetime" => 3600, - * "prefix" => "my", - * "index" => 1, - * ] - * ); - * - * $session->start(); - * - * $session->set("var", "some-value"); - * - * echo $session->get("var"); - * */ -class Redis extends \Phalcon\Session\Adapter +class Redis extends \Phalcon\Session\Adapter\AbstractAdapter { - protected $_redis = null; - - - protected $_lifetime = 8600; - - - - public function getRedis() {} - - - public function getLifetime() {} - /** - * Phalcon\Session\Adapter\Redis constructor + * Constructor * + * @param \Phalcon\Storage\AdapterFactory $factory * @param array $options */ - public function __construct(array $options = array()) {} - - /** - * {@inheritdoc} - * - * @return bool - */ - public function open() {} - - /** - * {@inheritdoc} - * - * @return bool - */ - public function close() {} - - /** - * {@inheritdoc} - * - * @param mixed $sessionId - * @return string - */ - public function read($sessionId) {} - - /** - * {@inheritdoc} - * - * @param string $sessionId - * @param string $data - * @return bool - */ - public function write($sessionId, $data) {} - - /** - * {@inheritdoc} - * - * @param mixed $sessionId - * @return bool - */ - public function destroy($sessionId = null) {} - - /** - * {@inheritdoc} - * - * @return bool - */ - public function gc() {} + public function __construct(\Phalcon\Storage\AdapterFactory $factory, array $options = array()) {} } diff --git a/src/Phalcon/session/adapter/Stream.php b/src/Phalcon/session/adapter/Stream.php new file mode 100644 index 00000000..50f4da55 --- /dev/null +++ b/src/Phalcon/session/adapter/Stream.php @@ -0,0 +1,70 @@ + '/tmp', + * ] + * ); + * $session->setHandler($files); + * ``` + */ +class Stream extends \Phalcon\Session\Adapter\Noop +{ + /** + * @var string + */ + private $path = ''; + + + /** + * @param array $options + */ + public function __construct(array $options = array()) {} + + /** + * @param mixed $id + * @return bool + */ + public function destroy($id): bool {} + + /** + * @param mixed $maxlifetime + * @return bool + */ + public function gc($maxlifetime): bool {} + + /** + * @param mixed $savePath + * @param mixed $sessionName + * @return bool + */ + public function open($savePath, $sessionName): bool {} + + /** + * @param mixed $id + * @return string + */ + public function read($id): string {} + + /** + * @param mixed $id + * @param mixed $data + * @return bool + */ + public function write($id, $data): bool {} + +} diff --git a/src/Phalcon/storage/AdapterFactory.php b/src/Phalcon/storage/AdapterFactory.php new file mode 100644 index 00000000..22477029 --- /dev/null +++ b/src/Phalcon/storage/AdapterFactory.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class AdapterFactory extends \Phalcon\Factory\AbstractFactory +{ + /** + * @var + */ + private $serializerFactory; + + + /** + * AdapterFactory constructor. + * + * @param \Phalcon\Storage\SerializerFactory $factory + * @param array $services + */ + public function __construct(\Phalcon\Storage\SerializerFactory $factory = null, array $services = array()) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @param array $options + * @return \Phalcon\Storage\Adapter\AbstractAdapter + */ + public function newInstance(string $name, array $options = array()): AbstractAdapter {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/storage/Exception.php b/src/Phalcon/storage/Exception.php new file mode 100644 index 00000000..e699f6fa --- /dev/null +++ b/src/Phalcon/storage/Exception.php @@ -0,0 +1,13 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class SerializerFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * SerializerFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * @param string name + * + * @throws Exception + * @param string $name + * @return \Phalcon\Storage\Serializer\SerializerInterface + */ + public function newInstance(string $name): SerializerInterface {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/storage/adapter/AbstractAdapter.php b/src/Phalcon/storage/adapter/AbstractAdapter.php new file mode 100644 index 00000000..ec177404 --- /dev/null +++ b/src/Phalcon/storage/adapter/AbstractAdapter.php @@ -0,0 +1,195 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +abstract class AbstractAdapter implements \Phalcon\Storage\Adapter\AdapterInterface +{ + /** + * @var mixed + */ + protected $adapter; + + /** + * Name of the default serializer class + * + * @var string + */ + protected $defaultSerializer = 'Php'; + + /** + * Name of the default TTL (time to live) + * + * @var int + */ + protected $lifetime = 3600; + + /** + * @var string + */ + protected $prefix = ''; + + /** + * Serializer + * + * @var + */ + protected $serializer; + + /** + * Serializer Factory + * + * @var + */ + protected $serializerFactory; + + + /** + * Name of the default serializer class + * + * @return string + */ + public function getDefaultSerializer(): string {} + + /** + * Name of the default serializer class + * + * @param string $defaultSerializer + */ + public function setDefaultSerializer(string $defaultSerializer) {} + + /** + * @return string + */ + public function getPrefix(): string {} + + /** + * Sets parameters based on options + * + * @param \Phalcon\Storage\SerializerFactory $factory + * @param array $options + */ + protected function __construct(\Phalcon\Storage\SerializerFactory $factory = null, array $options) {} + + /** + * Flushes/clears the cache + * + * @return bool + */ + abstract public function clear(): bool; + + /** + * Decrements a stored number + * + * @param string $key + * @param int $value + * @return int|bool + */ + abstract public function decrement(string $key, int $value = 1); + + /** + * Deletes data from the adapter + * + * @param string $key + * @return bool + */ + abstract public function delete(string $key): bool; + + /** + * Reads data from the adapter + * + * @param string $key + * @return mixed + */ + abstract public function get(string $key); + + /** + * Returns the adapter - connects to the storage if not connected + * + * @return mixed + */ + abstract public function getAdapter(); + + /** + * Returns all the keys stored + * + * @return array + */ + abstract public function getKeys(): array; + + /** + * Checks if an element exists in the cache + * + * @param string $key + * @return bool + */ + abstract public function has(string $key): bool; + + /** + * Increments a stored number + * + * @param string $key + * @param int $value + * @return int|bool + */ + abstract public function increment(string $key, int $value = 1); + + /** + * Stores data in the adapter + * + * @param string $key + * @param mixed $value + * @param mixed $ttl + * @return bool + */ + abstract public function set(string $key, $value, $ttl = null): bool; + + /** + * Returns the key requested, prefixed + * + * @param mixed $key + * @return string + */ + protected function getPrefixedKey($key): string {} + + /** + * Returns serialized data + * + * @param mixed $content + * @return mixed + */ + protected function getSerializedData($content) {} + + /** + * Calculates the TTL for a cache item + * + * @param DateInterval|int|null $ttl + * + * @throws Exception + * @param mixed $ttl + * @return int + */ + protected function getTtl($ttl): int {} + + /** + * Returns unserialized data + * + * @param mixed $content + * @param mixed $defaultValue + * @return mixed + */ + protected function getUnserializedData($content, $defaultValue = null) {} + + /** + * Initializes the serializer + */ + protected function initSerializer() {} + +} diff --git a/src/Phalcon/storage/adapter/AdapterInterface.php b/src/Phalcon/storage/adapter/AdapterInterface.php new file mode 100644 index 00000000..a7f35523 --- /dev/null +++ b/src/Phalcon/storage/adapter/AdapterInterface.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +abstract class AbstractSerializer implements \Phalcon\Storage\Serializer\SerializerInterface +{ + /** + * @var mixed + */ + protected $data = null; + + + /** + * @return mixed + */ + public function getData() {} + + /** + * @param mixed $data + */ + public function setData($data) {} + + /** + * Constructor + * + * @param mixed $data + */ + public function __construct($data = null) {} + + /** + * If this returns true, then the data returns back as is + * + * @param mixed $data + * @return bool + */ + protected function isSerializable($data): bool {} + +} diff --git a/src/Phalcon/storage/serializer/Base64.php b/src/Phalcon/storage/serializer/Base64.php new file mode 100644 index 00000000..6dfbad46 --- /dev/null +++ b/src/Phalcon/storage/serializer/Base64.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Base64 extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string + */ + public function serialize(): string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/Igbinary.php b/src/Phalcon/storage/serializer/Igbinary.php new file mode 100644 index 00000000..5047c4bc --- /dev/null +++ b/src/Phalcon/storage/serializer/Igbinary.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Igbinary extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string + */ + public function serialize(): string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/Json.php b/src/Phalcon/storage/serializer/Json.php new file mode 100644 index 00000000..ef79de7a --- /dev/null +++ b/src/Phalcon/storage/serializer/Json.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Json extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string + */ + public function serialize(): string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/Msgpack.php b/src/Phalcon/storage/serializer/Msgpack.php new file mode 100644 index 00000000..8b8a3e80 --- /dev/null +++ b/src/Phalcon/storage/serializer/Msgpack.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Msgpack extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string|null + */ + public function serialize(): ?string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/None.php b/src/Phalcon/storage/serializer/None.php new file mode 100644 index 00000000..bba29154 --- /dev/null +++ b/src/Phalcon/storage/serializer/None.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class None extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string + */ + public function serialize(): string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/Php.php b/src/Phalcon/storage/serializer/Php.php new file mode 100644 index 00000000..ea6e0ef6 --- /dev/null +++ b/src/Phalcon/storage/serializer/Php.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class Php extends \Phalcon\Storage\Serializer\AbstractSerializer +{ + + /** + * Serializes data + * + * @return string + */ + public function serialize(): string {} + + /** + * Unserializes data + * + * @param mixed $data + */ + public function unserialize($data) {} + +} diff --git a/src/Phalcon/storage/serializer/SerializerInterface.php b/src/Phalcon/storage/serializer/SerializerInterface.php new file mode 100644 index 00000000..b13acdd3 --- /dev/null +++ b/src/Phalcon/storage/serializer/SerializerInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +interface SerializerInterface extends \Serializable +{ + + /** + * @return mixed + */ + public function getData(); + + /** + * @param mixed $data + * @param $data + */ + public function setData($data); + +} diff --git a/src/Phalcon/tag/Select.php b/src/Phalcon/tag/Select.php index 551efc84..5f1f29fe 100644 --- a/src/Phalcon/tag/Select.php +++ b/src/Phalcon/tag/Select.php @@ -5,7 +5,8 @@ /** * Phalcon\Tag\Select * - * Generates a SELECT html tag using a static array of values or a Phalcon\Mvc\Model resultset + * Generates a SELECT html tag using a static array of values or a + * Phalcon\Mvc\Model resultset */ abstract class Select { @@ -15,26 +16,29 @@ abstract class Select * * @param array $parameters * @param array $data + * @return string */ - public static function selectField($parameters, $data = null) {} + public static function selectField($parameters, $data = null): string {} /** - * Generate the OPTION tags based on a resultset + * Generate the OPTION tags based on an array * - * @param \Phalcon\Mvc\Model\Resultset $resultset - * @param array $using + * @param array $data * @param mixed $value * @param string $closeOption + * @return string */ - private static function _optionsFromResultset($resultset, $using, $value, $closeOption) {} + private static function optionsFromArray(array $data, $value, string $closeOption): string {} /** - * Generate the OPTION tags based on an array + * Generate the OPTION tags based on a resultset * - * @param array $data + * @param \Phalcon\Mvc\Model\ResulsetInterface $resultset + * @param array $using * @param mixed $value * @param string $closeOption + * @return string */ - private static function _optionsFromArray($data, $value, $closeOption) {} + private static function optionsFromResultset(\Phalcon\Mvc\Model\ResulsetInterface $resultset, $using, $value, string $closeOption): string {} } diff --git a/src/Phalcon/translate/Factory.php b/src/Phalcon/translate/Factory.php deleted file mode 100644 index a33f5973..00000000 --- a/src/Phalcon/translate/Factory.php +++ /dev/null @@ -1,30 +0,0 @@ - - * use Phalcon\Translate\Factory; - * - * $options = [ - * "locale" => "de_DE.UTF-8", - * "defaultDomain" => "translations", - * "directory" => "/path/to/application/locales", - * "category" => LC_MESSAGES, - * "adapter" => "gettext", - * ]; - * $translate = Factory::load($options); - * - */ -class Factory extends \Phalcon\Factory -{ - - /** - * @param \Phalcon\Config|array $config - * @return AdapterInterface - */ - public static function load($config) {} - -} diff --git a/src/Phalcon/translate/InterpolatorFactory.php b/src/Phalcon/translate/InterpolatorFactory.php new file mode 100644 index 00000000..5907eda6 --- /dev/null +++ b/src/Phalcon/translate/InterpolatorFactory.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class InterpolatorFactory extends \Phalcon\Factory\AbstractFactory +{ + /** + * @var array + */ + private $mapper = array(); + + /** + * @var array + */ + private $services = array(); + + + /** + * AdapterFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @return \Phalcon\Translate\Adapter\AdapterInterface + */ + public function newInstance(string $name): AdapterInterface {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/translate/InterpolatorInterface.php b/src/Phalcon/translate/InterpolatorInterface.php deleted file mode 100644 index ebd37966..00000000 --- a/src/Phalcon/translate/InterpolatorInterface.php +++ /dev/null @@ -1,22 +0,0 @@ - + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class TranslateFactory extends \Phalcon\Factory\AbstractFactory +{ + /** + * @var InterpolatorFactory + */ + private $interpolator; + + + /** + * AdapterFactory constructor. + * + * @param \Phalcon\Translate\InterpolatorFactory $interpolator + * @param array $services + */ + public function __construct(\Phalcon\Translate\InterpolatorFactory $interpolator, array $services = array()) {} + + /** + * Factory to create an instace from a Config object + * + * @param mixed $config + * @return mixed + */ + public function load($config) {} + + /** + * Create a new instance of the adapter + * + * @param string $name + * @param array $options + * @return AbstractAdapter + */ + public function newInstance(string $name, array $options = array()): AbstractAdapter {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/translate/Adapter.php b/src/Phalcon/translate/adapter/AbstractAdapter.php similarity index 58% rename from src/Phalcon/translate/Adapter.php rename to src/Phalcon/translate/adapter/AbstractAdapter.php index 42b3d83b..8d221db3 100644 --- a/src/Phalcon/translate/Adapter.php +++ b/src/Phalcon/translate/adapter/AbstractAdapter.php @@ -1,79 +1,79 @@ + * ```php * use Phalcon\Translate\Adapter\Gettext; * * $adapter = new Gettext( @@ -16,72 +16,60 @@ * "category" => LC_MESSAGES, * ] * ); - * + * ``` * * Allows translate using gettext */ -class Gettext extends \Phalcon\Translate\Adapter implements \ArrayAccess +class Gettext extends \Phalcon\Translate\Adapter\AbstractAdapter implements \ArrayAccess { /** - * @var string|array + * @var int */ - protected $_directory; + protected $category; /** * @var string */ - protected $_defaultDomain; + protected $defaultDomain; /** - * @var string + * @var string|array */ - protected $_locale; + protected $directory; /** - * @var int + * @var string */ - protected $_category; + protected $locale; /** - * @return string|array + * @return int */ - public function getDirectory() {} + public function getCategory(): int {} /** * @return string */ - public function getDefaultDomain() {} + public function getDefaultDomain(): string {} /** - * @return string + * @return string|array */ - public function getLocale() {} + public function getDirectory() {} /** - * @return int + * @return string */ - public function getCategory() {} + public function getLocale(): string {} /** * Phalcon\Translate\Adapter\Gettext constructor * + * @param \Phalcon\Translate\InterpolatorFactory $interpolator * @param array $options */ - public function __construct(array $options) {} - - /** - * Returns the translation related to the given key. - * - * - * $translator->query("你好 %name%!", ["name" => "Phalcon"]); - * - * - * @param string $index - * @param mixed $placeholders - * @return string - */ - public function query($index, $placeholders = null) {} + public function __construct(\Phalcon\Translate\InterpolatorFactory $interpolator, array $options) {} /** * Check whether is defined a translation key in the internal array @@ -89,11 +77,12 @@ public function query($index, $placeholders = null) {} * @param string $index * @return bool */ - public function exists($index) {} + public function exists(string $index): bool {} /** * The plural version of gettext(). - * Some languages have more than one form for plural messages dependent on the count. + * Some languages have more than one form for plural messages dependent on + * the count. * * @param string $msgid1 * @param string $msgid2 @@ -102,34 +91,39 @@ public function exists($index) {} * @param string $domain * @return string */ - public function nquery($msgid1, $msgid2, $count, $placeholders = null, $domain = null) {} + public function nquery(string $msgid1, string $msgid2, int $count, $placeholders = null, string $domain = null): string {} /** - * Changes the current domain (i.e. the translation file) + * Returns the translation related to the given key. * - * @param mixed $domain + * ```php + * $translator->query("你好 %name%!", ["name" => "Phalcon"]); + * ``` + * + * @param string $index + * @param array $placeholders * @return string */ - public function setDomain($domain) {} + public function query(string $index, $placeholders = null): string {} /** * Sets the default domain * * @return string */ - public function resetDomain() {} + public function resetDomain(): string {} /** * Sets the domain default to search within when calls are made to gettext() * * @param string $domain */ - public function setDefaultDomain($domain) {} + public function setDefaultDomain(string $domain) {} /** * Sets the path for a domain * - * + * ```php * // Set the directory path * $gettext->setDirectory("/path/to/the/messages"); * @@ -140,41 +134,49 @@ public function setDefaultDomain($domain) {} * "another" => "/path/to/the/another", * ] * ); - * + * ``` * * @param string|array $directory The directory path or an array of directories and domains */ public function setDirectory($directory) {} + /** + * Changes the current domain (i.e. the translation file) + * + * @param mixed $domain + * @return string + */ + public function setDomain($domain): string {} + /** * Sets locale information * - * + * ```php * // Set locale to Dutch * $gettext->setLocale(LC_ALL, "nl_NL"); * * // Try different possible locale names for german * $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); - * + * ``` * * @param int $category * @param string $locale * @return string|bool */ - public function setLocale($category, $locale) {} + public function setLocale(int $category, string $locale) {} /** - * Validator for constructor + * Gets default options * - * @param array $options + * @return array */ - protected function prepareOptions(array $options) {} + protected function getOptionsDefault(): array {} /** - * Gets default options + * Validator for constructor * - * @return array + * @param array $options */ - protected function getOptionsDefault() {} + protected function prepareOptions(array $options) {} } diff --git a/src/Phalcon/translate/adapter/NativeArray.php b/src/Phalcon/translate/adapter/NativeArray.php index bd5f98c6..710d5661 100644 --- a/src/Phalcon/translate/adapter/NativeArray.php +++ b/src/Phalcon/translate/adapter/NativeArray.php @@ -7,34 +7,50 @@ * * Allows to define translation lists using PHP arrays */ -class NativeArray extends \Phalcon\Translate\Adapter implements \ArrayAccess +class NativeArray extends \Phalcon\Translate\Adapter\AbstractAdapter implements \ArrayAccess { + /** + * @var array + */ + private $translate; - protected $_translate; + /** + * @var bool + */ + private $triggerError = false; /** * Phalcon\Translate\Adapter\NativeArray constructor * + * @param \Phalcon\Translate\InterpolatorFactory $interpolator * @param array $options */ - public function __construct(array $options) {} + public function __construct(\Phalcon\Translate\InterpolatorFactory $interpolator, array $options) {} /** - * Returns the translation related to the given key + * Check whether is defined a translation key in the internal array + * + * @param string $index + * @return bool + */ + public function exists(string $index): bool {} + + /** + * Whenever a key is not found this medhod will be called * * @param string $index - * @param mixed $placeholders * @return string */ - public function query($index, $placeholders = null) {} + public function notFound(string $index): string {} /** - * Check whether is defined a translation key in the internal array + * Returns the translation related to the given key * * @param string $index - * @return bool + * @param mixed $placeholders + * @return string */ - public function exists($index) {} + public function query(string $index, $placeholders = null): string {} } diff --git a/src/Phalcon/translate/interpolator/AssociativeArray.php b/src/Phalcon/translate/interpolator/AssociativeArray.php index cfb6f050..55bc4363 100644 --- a/src/Phalcon/translate/interpolator/AssociativeArray.php +++ b/src/Phalcon/translate/interpolator/AssociativeArray.php @@ -2,17 +2,24 @@ namespace Phalcon\Translate\Interpolator; - -class AssociativeArray implements \Phalcon\Translate\InterpolatorInterface +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class AssociativeArray implements \Phalcon\Translate\Interpolator\InterpolatorInterface { /** * Replaces placeholders by the values passed * * @param string $translation - * @param mixed $placeholders + * @param array $placeholders * @return string */ - public function replacePlaceholders($translation, $placeholders = null) {} + public function replacePlaceholders(string $translation, array $placeholders = array()): string {} } diff --git a/src/Phalcon/translate/interpolator/IndexedArray.php b/src/Phalcon/translate/interpolator/IndexedArray.php index f668236e..af57aa6f 100644 --- a/src/Phalcon/translate/interpolator/IndexedArray.php +++ b/src/Phalcon/translate/interpolator/IndexedArray.php @@ -2,17 +2,24 @@ namespace Phalcon\Translate\Interpolator; - -class IndexedArray implements \Phalcon\Translate\InterpolatorInterface +/** + * This file is part of the Phalcon Framework. + * + * (c) Phalcon Team + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class IndexedArray implements \Phalcon\Translate\Interpolator\InterpolatorInterface { /** * Replaces placeholders by the values passed * * @param string $translation - * @param mixed $placeholders + * @param array $placeholders * @return string */ - public function replacePlaceholders($translation, $placeholders = null) {} + public function replacePlaceholders(string $translation, array $placeholders = array()): string {} } diff --git a/src/Phalcon/translate/interpolator/InterpolatorInterface.php b/src/Phalcon/translate/interpolator/InterpolatorInterface.php new file mode 100644 index 00000000..4adb6a41 --- /dev/null +++ b/src/Phalcon/translate/interpolator/InterpolatorInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE.txt + * file that was distributed with this source code. + */ +class ValidatorFactory extends \Phalcon\Factory\AbstractFactory +{ + + /** + * TagFactory constructor. + * + * @param array $services + */ + public function __construct(array $services = array()) {} + + /** + * Creates a new instance + * + * @param string $name + * @return mixed + */ + public function newInstance(string $name) {} + + /** + * @return array + */ + protected function getAdapters(): array {} + +} diff --git a/src/Phalcon/validation/ValidatorInterface.php b/src/Phalcon/validation/ValidatorInterface.php index 5cf7d765..307747be 100644 --- a/src/Phalcon/validation/ValidatorInterface.php +++ b/src/Phalcon/validation/ValidatorInterface.php @@ -3,38 +3,68 @@ namespace Phalcon\Validation; /** - * Phalcon\Validation\ValidatorInterface - * - * Interface for Phalcon\Validation\Validator + * Interface for Phalcon\Validation\AbstractValidator */ interface ValidatorInterface { /** - * Checks if an option is defined + * Returns an option in the validator's options + * Returns null if the option hasn't set * * @param string $key - * @return bool + * @param mixed $defaultValue + * @return mixed */ - public function hasOption($key); + public function getOption(string $key, $defaultValue = null); /** - * Returns an option in the validator's options - * Returns null if the option hasn't set + * Checks if an option is defined * * @param string $key - * @param mixed $defaultValue - * @return mixed + * @return bool */ - public function getOption($key, $defaultValue = null); + public function hasOption(string $key): bool; /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $attribute + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $attribute); + public function validate(\Phalcon\Validation $validation, $field): bool; + + /** + * Get the template message + * + * @throw InvalidArgumentException When the field does not exists + * @param string $field + * @return string + */ + public function getTemplate(string $field): string; + + /** + * Get message templates + * + * @return array + */ + public function getTemplates(): array; + + /** + * Clear current template and set new from an array, + * + * @param array $templates + * @return ValidatorInterface + */ + public function setTemplates(array $templates): ValidatorInterface; + + /** + * Set a new temlate message + * + * @param string $template + * @return ValidatorInterface + */ + public function setTemplate(string $template): ValidatorInterface; } diff --git a/src/Phalcon/validation/message/Group.php b/src/Phalcon/validation/message/Group.php deleted file mode 100644 index 34a8301c..00000000 --- a/src/Phalcon/validation/message/Group.php +++ /dev/null @@ -1,155 +0,0 @@ - - * print_r( - * $messages[0] - * ); - * - * - * @param int $index - * @return bool|\Phalcon\Validation\Message - */ - public function offsetGet($index) {} - - /** - * Sets an attribute using the array-syntax - * - * - * $messages[0] = new \Phalcon\Validation\Message("This is a message"); - * - * - * @param int $index - * @param \Phalcon\Validation\Message $message - */ - public function offsetSet($index, $message) {} - - /** - * Checks if an index exists - * - * - * var_dump( - * isset($message["database"]) - * ); - * - * - * @param int $index - * @return bool - */ - public function offsetExists($index) {} - - /** - * Removes a message from the list - * - * - * unset($message["database"]); - * - * - * @param mixed $index - */ - public function offsetUnset($index) {} - - /** - * Appends a message to the group - * - * - * $messages->appendMessage( - * new \Phalcon\Validation\Message("This is a message") - * ); - * - * - * @param \Phalcon\Validation\MessageInterface $message - */ - public function appendMessage(\Phalcon\Validation\MessageInterface $message) {} - - /** - * Appends an array of messages to the group - * - * - * $messages->appendMessages($messagesArray); - * - * - * @param \Phalcon\Validation\MessageInterface[] $messages - */ - public function appendMessages($messages) {} - - /** - * Filters the message group by field name - * - * @param string $fieldName - * @return array - */ - public function filter($fieldName) {} - - /** - * Returns the number of messages in the list - * - * @return int - */ - public function count() {} - - /** - * Rewinds the internal iterator - */ - public function rewind() {} - - /** - * Returns the current message in the iterator - * - * @return \Phalcon\Validation\Message - */ - public function current() {} - - /** - * Returns the current position/key in the iterator - * - * @return int - */ - public function key() {} - - /** - * Moves the internal iteration pointer to the next position - */ - public function next() {} - - /** - * Check if the current message in the iterator is valid - * - * @return bool - */ - public function valid() {} - - /** - * Magic __set_state helps to re-build messages variable when exporting - * - * @param array $group - * @return \Phalcon\Validation\Message\Group - */ - public static function __set_state($group) {} - -} diff --git a/src/Phalcon/validation/validator/Alnum.php b/src/Phalcon/validation/validator/Alnum.php index c73c1ad4..e44a4154 100644 --- a/src/Phalcon/validation/validator/Alnum.php +++ b/src/Phalcon/validation/validator/Alnum.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Alnum - * * Check for alphanumeric character(s) * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Alnum as AlnumValidator; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Alnum extends \Phalcon\Validation\Validator +class Alnum extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must contain only letters and numbers'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Alpha.php b/src/Phalcon/validation/validator/Alpha.php index 87c1dd50..c4a0ef8c 100644 --- a/src/Phalcon/validation/validator/Alpha.php +++ b/src/Phalcon/validation/validator/Alpha.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Alpha - * * Check for alphabetic character(s) * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Alpha as AlphaValidator; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Alpha extends \Phalcon\Validation\Validator +class Alpha extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must contain only letters'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Between.php b/src/Phalcon/validation/validator/Between.php index a6ec67a6..62ae2db7 100644 --- a/src/Phalcon/validation/validator/Between.php +++ b/src/Phalcon/validation/validator/Between.php @@ -3,12 +3,10 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Between - * * Validates that a value is between an inclusive range of two values. * For a value x, the test is passed if minimum<=x<=maximum. * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Between; * @@ -47,18 +45,21 @@ * ] * ) * ); - * + * ``` */ -class Between extends \Phalcon\Validation\Validator +class Between extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be within the range of :min to :max'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Callback.php b/src/Phalcon/validation/validator/Callback.php index 6915f1e6..61c7a9fa 100644 --- a/src/Phalcon/validation/validator/Callback.php +++ b/src/Phalcon/validation/validator/Callback.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Callback - * * Calls user function for validation * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Callback as CallbackValidator; * use Phalcon\Validation\Validator\Numericality as NumericalityValidator; @@ -46,18 +44,21 @@ * ] * ) * ); - * + * ``` */ -class Callback extends \Phalcon\Validation\Validator +class Callback extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must match the callback function'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Confirmation.php b/src/Phalcon/validation/validator/Confirmation.php index 2c235c3d..9adbf563 100644 --- a/src/Phalcon/validation/validator/Confirmation.php +++ b/src/Phalcon/validation/validator/Confirmation.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Confirmation - * * Checks that two values have the same value * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Confirmation; * @@ -41,19 +39,22 @@ * ] * ) * ); - * + * ``` */ -class Confirmation extends \Phalcon\Validation\Validator +class Confirmation extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be the same as :with'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} /** * Compare strings @@ -62,6 +63,6 @@ public function validate(\Phalcon\Validation $validation, $field) {} * @param string $b * @return bool */ - protected final function compare($a, $b) {} + final protected function compare(string $a, string $b): bool {} } diff --git a/src/Phalcon/validation/validator/CreditCard.php b/src/Phalcon/validation/validator/CreditCard.php index fcef5b6f..659e1445 100644 --- a/src/Phalcon/validation/validator/CreditCard.php +++ b/src/Phalcon/validation/validator/CreditCard.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\CreditCard - * * Checks if a value has a valid credit card number * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; * @@ -36,26 +34,30 @@ * ] * ) * ); - * + * ``` */ -class CreditCard extends \Phalcon\Validation\Validator +class CreditCard extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field is not valid for a credit card number'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} /** - * is a simple checksum formula used to validate a variety of identification numbers + * is a simple checksum formula used to validate a variety of identification + * numbers * * @param string $number * @return bool */ - private function verifyByLuhnAlgorithm($number) {} + private function verifyByLuhnAlgorithm(string $number): bool {} } diff --git a/src/Phalcon/validation/validator/Date.php b/src/Phalcon/validation/validator/Date.php index f5a354ed..47ce72e1 100644 --- a/src/Phalcon/validation/validator/Date.php +++ b/src/Phalcon/validation/validator/Date.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Date - * * Checks if a value is a valid date * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Date as DateValidator; * @@ -41,25 +39,28 @@ * ] * ) * ); - * + * ``` */ -class Date extends \Phalcon\Validation\Validator +class Date extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field is not a valid date'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} /** * @param mixed $value * @param mixed $format * @return bool */ - private function checkDate($value, $format) {} + private function checkDate($value, $format): bool {} } diff --git a/src/Phalcon/validation/validator/Digit.php b/src/Phalcon/validation/validator/Digit.php index 4bcc361b..038cb5d8 100644 --- a/src/Phalcon/validation/validator/Digit.php +++ b/src/Phalcon/validation/validator/Digit.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Digit - * * Check for numeric character(s) * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Digit as DigitValidator; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Digit extends \Phalcon\Validation\Validator +class Digit extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be numeric'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Email.php b/src/Phalcon/validation/validator/Email.php index 804d42f2..93b774b3 100644 --- a/src/Phalcon/validation/validator/Email.php +++ b/src/Phalcon/validation/validator/Email.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Email - * * Checks if a value has a correct e-mail format * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Email as EmailValidator; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Email extends \Phalcon\Validation\Validator +class Email extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be an email address'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Exception.php b/src/Phalcon/validation/validator/Exception.php index 6e0f3fbf..240b1809 100644 --- a/src/Phalcon/validation/validator/Exception.php +++ b/src/Phalcon/validation/validator/Exception.php @@ -3,9 +3,8 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Exception - * - * Exceptions thrown in Phalcon\Validation\Validator\ classes will use this class + * Exceptions thrown in Phalcon\Validation\Validator\ classes will use this + * class */ class Exception extends \Phalcon\Exception { diff --git a/src/Phalcon/validation/validator/ExclusionIn.php b/src/Phalcon/validation/validator/ExclusionIn.php index f4eac992..aa870b04 100644 --- a/src/Phalcon/validation/validator/ExclusionIn.php +++ b/src/Phalcon/validation/validator/ExclusionIn.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\ExclusionIn - * * Check if a value is not included into a list of values * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\ExclusionIn; * @@ -47,18 +45,21 @@ * ] * ) * ); - * + * ``` */ -class ExclusionIn extends \Phalcon\Validation\Validator +class ExclusionIn extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must not be a part of list: :domain'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/File.php b/src/Phalcon/validation/validator/File.php index aef472d0..3ab08575 100644 --- a/src/Phalcon/validation/validator/File.php +++ b/src/Phalcon/validation/validator/File.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\File - * * Checks if a value has a correct file * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\File as FileValidator; * @@ -18,14 +16,14 @@ * new FileValidator( * [ * "maxSize" => "2M", - * "messageSize" => ":field exceeds the max filesize (:max)", + * "messageSize" => ":field exceeds the max filesize (:size)", * "allowedTypes" => [ * "image/jpeg", * "image/png", * ], * "messageType" => "Allowed file types are :types", * "maxResolution" => "800x600", - * "messageMaxResolution" => "Max resolution of :field is :max", + * "messageMaxResolution" => "Max resolution of :field is :resolution", * ] * ) * ); @@ -69,27 +67,16 @@ * ] * ) * ); - * + * ``` */ -class File extends \Phalcon\Validation\Validator +class File extends \Phalcon\Validation\AbstractValidatorComposite { /** - * Executes the validation - * - * @param \Phalcon\Validation $validation - * @param string $field - * @return bool - */ - public function validate(\Phalcon\Validation $validation, $field) {} - - /** - * Check on empty + * Constructor * - * @param \Phalcon\Validation $validation - * @param string $field - * @return bool + * @param array $options */ - public function isAllowEmpty(\Phalcon\Validation $validation, $field) {} + public function __construct(array $options = array()) {} } diff --git a/src/Phalcon/validation/validator/Identical.php b/src/Phalcon/validation/validator/Identical.php index 9a28f586..152a25ab 100644 --- a/src/Phalcon/validation/validator/Identical.php +++ b/src/Phalcon/validation/validator/Identical.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Identical - * * Checks if a value is identical to other * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Identical; * @@ -41,18 +39,21 @@ * ] * ) * ); - * + * ``` */ -class Identical extends \Phalcon\Validation\Validator +class Identical extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field does not have the expected value'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/InclusionIn.php b/src/Phalcon/validation/validator/InclusionIn.php index b55343d3..2b69130e 100644 --- a/src/Phalcon/validation/validator/InclusionIn.php +++ b/src/Phalcon/validation/validator/InclusionIn.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\InclusionIn - * * Check if a value is included into a list of values * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\InclusionIn; * @@ -41,18 +39,21 @@ * ] * ) * ); - * + * ``` */ -class InclusionIn extends \Phalcon\Validation\Validator +class InclusionIn extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be a part of list: :domain'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Ip.php b/src/Phalcon/validation/validator/Ip.php index 7193c835..485fdb5b 100644 --- a/src/Phalcon/validation/validator/Ip.php +++ b/src/Phalcon/validation/validator/Ip.php @@ -2,27 +2,21 @@ namespace Phalcon\Validation\Validator; -use Phalcon\Validation; -use Phalcon\Validation\Validator; -use Phalcon\Messages\Message; - /** - * Phalcon\Validation\Validator\ip - * - * Check for ip addresses + * Check for IP addresses * - * + * ```php * use Phalcon\Validation\Validator\Ip as IpValidator; * * $validator->add( * "ip_address", * new IpValidator( * [ - * "message" => ":field must contain only ip addresses", - * "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + * "message" => ":field must contain only ip addresses", + * "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified * "allowReserved" => false, // False if not specified. Ignored for v6 - * "allowPrivate" => false, // False if not specified - * "allowEmpty" => false, + * "allowPrivate" => false, // False if not specified + * "allowEmpty" => false, * ] * ) * ); @@ -35,39 +29,49 @@ * new IpValidator( * [ * "message" => [ - * "source_address" => "source_address must contain only ip addresses", - * "destination_address" => "destination_address must contain only ip addresses", + * "source_address" => "source_address must be a valid IP address", + * "destination_address" => "destination_address must be a valid IP address", * ], * "version" => [ - * "source_address" => Ip::VERSION_4 | IP::VERSION_6, + * "source_address" => Ip::VERSION_4 | IP::VERSION_6, * "destination_address" => Ip::VERSION_4, * ], * "allowReserved" => [ - * "source_address" => false, + * "source_address" => false, * "destination_address" => true, * ], * "allowPrivate" => [ - * "source_address" => false, + * "source_address" => false, * "destination_address" => true, * ], * "allowEmpty" => [ - * "source_address" => false, + * "source_address" => false, * "destination_address" => true, * ], * ] * ) * ); - * + * ``` */ -class Ip extends Validator +class Ip extends \Phalcon\Validation\AbstractValidator { - const VERSION_4 = FILTER_FLAG_IPV4; - const VERSION_6 = FILTER_FLAG_IPV6; - /** - * Executes the validation - */ - public function validate(Validation $validation, $field) : bool - { - } + const VERSION_4 = 1048576; + + + const VERSION_6 = 2097152; + + + protected $template = 'Field :field must be a valid IP address'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + } diff --git a/src/Phalcon/validation/validator/Numericality.php b/src/Phalcon/validation/validator/Numericality.php index baf05fe8..4a55030b 100644 --- a/src/Phalcon/validation/validator/Numericality.php +++ b/src/Phalcon/validation/validator/Numericality.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Numericality - * * Check for a valid numeric value * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Numericality; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Numericality extends \Phalcon\Validation\Validator +class Numericality extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field does not have a valid numeric format'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/PresenceOf.php b/src/Phalcon/validation/validator/PresenceOf.php index 046f395b..f7e1a631 100644 --- a/src/Phalcon/validation/validator/PresenceOf.php +++ b/src/Phalcon/validation/validator/PresenceOf.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\PresenceOf - * * Validates that a value is not null or empty string * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\PresenceOf; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class PresenceOf extends \Phalcon\Validation\Validator +class PresenceOf extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field is required'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/Regex.php b/src/Phalcon/validation/validator/Regex.php index f3f431b9..23aa7ec5 100644 --- a/src/Phalcon/validation/validator/Regex.php +++ b/src/Phalcon/validation/validator/Regex.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Regex - * * Allows validate if the value of a field matches a regular expression * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Regex as RegexValidator; * @@ -41,18 +39,21 @@ * ] * ) * ); - * + * ``` */ -class Regex extends \Phalcon\Validation\Validator +class Regex extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field does not match the required format'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/StringLength.php b/src/Phalcon/validation/validator/StringLength.php index b95904f7..7cded7d9 100644 --- a/src/Phalcon/validation/validator/StringLength.php +++ b/src/Phalcon/validation/validator/StringLength.php @@ -3,13 +3,12 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\StringLength - * * Validates that a string has the specified maximum and minimum constraints * The test is passed if for a string's length L, min<=L<=max, i.e. L must * be at least min, and at most max. + * Since Phalcon v4.0 this valitor works like a container * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\StringLength as StringLength; * @@ -19,10 +18,12 @@ * "name_last", * new StringLength( * [ - * "max" => 50, - * "min" => 2, - * "messageMaximum" => "We don't like really long names", - * "messageMinimum" => "We want more than just their initials", + * "max" => 50, + * "min" => 2, + * "messageMaximum" => "We don't like really long names", + * "messageMinimum" => "We want more than just their initials", + * "includedMaximum" => true, + * "includedMinimum" => false, * ] * ) * ); @@ -49,22 +50,28 @@ * "messageMinimum" => [ * "name_last" => "We don't like too short last names", * "name_first" => "We don't like too short first names", + * ], + * "includedMaximum" => [ + * "name_last" => false, + * "name_first" => true, + * ], + * "includedMinimum" => [ + * "name_last" => false, + * "name_first" => true, * ] * ] * ) * ); - * + * ``` */ -class StringLength extends \Phalcon\Validation\Validator +class StringLength extends \Phalcon\Validation\AbstractValidatorComposite { /** - * Executes the validation + * Constructor * - * @param \Phalcon\Validation $validation - * @param string $field - * @return bool + * @param array $options */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function __construct(array $options = array()) {} } diff --git a/src/Phalcon/validation/validator/Uniqueness.php b/src/Phalcon/validation/validator/Uniqueness.php index 26b77fb4..fa70ed86 100644 --- a/src/Phalcon/validation/validator/Uniqueness.php +++ b/src/Phalcon/validation/validator/Uniqueness.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Uniqueness - * * Check that a field is unique in the related table * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; * @@ -22,10 +20,10 @@ * ] * ) * ); - * + * ``` * * Different attribute from the field: - * + * ```php * $validator->add( * "username", * new UniquenessValidator( @@ -35,18 +33,18 @@ * ] * ) * ); - * + * ``` * * In model: - * + * ```php * $validator->add( * "username", * new UniquenessValidator() * ); - * + * ``` * * Combination of fields in model: - * + * ```php * $validator->add( * [ * "firstName", @@ -54,12 +52,12 @@ * ], * new UniquenessValidator() * ); - * + * ``` * * It is possible to convert values before validation. This is useful in * situations where values need to be converted to do the database lookup: * - * + * ```php * $validator->add( * "username", * new UniquenessValidator( @@ -72,11 +70,14 @@ * ] * ) * ); - * + * ``` */ -class Uniqueness extends \Phalcon\Validation\CombinedFieldsValidator +class Uniqueness extends \Phalcon\Validation\AbstractCombinedFieldsValidator { + protected $template = 'Field :field must be unique'; + + private $columnMap = null; @@ -87,14 +88,7 @@ class Uniqueness extends \Phalcon\Validation\CombinedFieldsValidator * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} - - /** - * @param \Phalcon\Validation $validation - * @param mixed $field - * @return bool - */ - protected function isUniqueness(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} /** * The column map is used in the case to get real column name @@ -103,24 +97,31 @@ protected function isUniqueness(\Phalcon\Validation $validation, $field) {} * @param string $field * @return string */ - protected function getColumnNameReal($record, $field) {} + protected function getColumnNameReal($record, string $field): string {} /** - * Uniqueness method used for model + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + protected function isUniqueness(\Phalcon\Validation $validation, $field): bool {} + + /** + * Uniqueness method used for collection * * @param mixed $record * @param array $field * @param array $values */ - protected function isUniquenessModel($record, array $field, array $values) {} + protected function isUniquenessCollection($record, array $field, array $values) {} /** - * Uniqueness method used for collection + * Uniqueness method used for model * * @param mixed $record * @param array $field * @param array $values */ - protected function isUniquenessCollection($record, array $field, array $values) {} + protected function isUniquenessModel($record, array $field, array $values) {} } diff --git a/src/Phalcon/validation/validator/Url.php b/src/Phalcon/validation/validator/Url.php index b3e86bd5..0c85f1f0 100644 --- a/src/Phalcon/validation/validator/Url.php +++ b/src/Phalcon/validation/validator/Url.php @@ -3,11 +3,9 @@ namespace Phalcon\Validation\Validator; /** - * Phalcon\Validation\Validator\Url - * * Checks if a value has a url format * - * + * ```php * use Phalcon\Validation; * use Phalcon\Validation\Validator\Url as UrlValidator; * @@ -36,18 +34,21 @@ * ] * ) * ); - * + * ``` */ -class Url extends \Phalcon\Validation\Validator +class Url extends \Phalcon\Validation\AbstractValidator { + protected $template = 'Field :field must be a url'; + + /** * Executes the validation * * @param \Phalcon\Validation $validation - * @param string $field + * @param mixed $field * @return bool */ - public function validate(\Phalcon\Validation $validation, $field) {} + public function validate(\Phalcon\Validation $validation, $field): bool {} } diff --git a/src/Phalcon/validation/validator/file/AbstractFile.php b/src/Phalcon/validation/validator/file/AbstractFile.php new file mode 100644 index 00000000..2a2c15cd --- /dev/null +++ b/src/Phalcon/validation/validator/file/AbstractFile.php @@ -0,0 +1,151 @@ +add( + * "file", + * new Size( + * [ + * "maxSize" => "2M", + * "messageSize" => ":field exceeds the max filesize (:size)", + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new FileValidator( + * [ + * "maxSize" => [ + * "file" => "2M", + * "anotherFile" => "4M", + * ], + * "messageSize" => [ + * "file" => "file exceeds the max filesize 2M", + * "anotherFile" => "anotherFile exceeds the max filesize 4M", + * ], + * ] + * ) + * ); + * ``` + */ +abstract class AbstractFile extends \Phalcon\Validation\AbstractValidator +{ + /** + * Empty is empty + */ + protected $messageFileEmpty = 'Field :field must not be empty'; + + /** + * File exceeed the file size setted in PHP configuration + */ + protected $messageIniSize = 'File :field exceeds the maximum file size'; + + /** + * File is not valid + */ + protected $messageValid = 'Field :field is not valid'; + + + /** + * Empty is empty + */ + public function getMessageFileEmpty() {} + + /** + * Empty is empty + * + * @param mixed $messageFileEmpty + */ + public function setMessageFileEmpty($messageFileEmpty) {} + + /** + * File exceeed the file size setted in PHP configuration + */ + public function getMessageIniSize() {} + + /** + * File exceeed the file size setted in PHP configuration + * + * @param mixed $messageIniSize + */ + public function setMessageIniSize($messageIniSize) {} + + /** + * File is not valid + */ + public function getMessageValid() {} + + /** + * File is not valid + * + * @param mixed $messageValid + */ + public function setMessageValid($messageValid) {} + + /** + * Check on empty + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function isAllowEmpty(\Phalcon\Validation $validation, string $field): bool {} + + /** + * Check upload + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function checkUpload(\Phalcon\Validation $validation, $field): bool {} + + /** + * Check if uploaded file is larger than PHP allowed size + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function checkUploadMaxSize(\Phalcon\Validation $validation, $field): bool {} + + /** + * Check if upload is empty + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function checkUploadIsEmpty(\Phalcon\Validation $validation, $field): bool {} + + /** + * Check if upload is valid + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function checkUploadIsValid(\Phalcon\Validation $validation, $field): bool {} + + /** + * Convert a string like "2.5MB" in bytes + * + * @param string $size + * @return double + */ + public function getFileSizeInBytes(string $size): float {} + +} diff --git a/src/Phalcon/validation/validator/file/MimeType.php b/src/Phalcon/validation/validator/file/MimeType.php new file mode 100644 index 00000000..b642b371 --- /dev/null +++ b/src/Phalcon/validation/validator/file/MimeType.php @@ -0,0 +1,68 @@ +add( + * "file", + * new MimeType( + * [ + * "types" => [ + * "image/jpeg", + * "image/png", + * ], + * "message" => "Allowed file types are :types" + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new MimeType( + * [ + * "types" => [ + * "file" => [ + * "image/jpeg", + * "image/png", + * ], + * "anotherFile" => [ + * "image/gif", + * "image/bmp", + * ], + * ], + * "message" => [ + * "file" => "Allowed file types are image/jpeg and image/png", + * "anotherFile" => "Allowed file types are image/gif and image/bmp", + * ] + * ] + * ) + * ); + * ``` + */ +class MimeType extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field must be of type: :types'; + + + /** + * Executes the validation + * + * @param Valiation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/resolution/Equal.php b/src/Phalcon/validation/validator/file/resolution/Equal.php new file mode 100644 index 00000000..cc59fdd6 --- /dev/null +++ b/src/Phalcon/validation/validator/file/resolution/Equal.php @@ -0,0 +1,59 @@ +add( + * "file", + * new Equal( + * [ + * "resolution" => "800x600", + * "message" => "The resolution of the field :field has to be equal :resolution", + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Equal( + * [ + * "resolution" => [ + * "file" => "800x600", + * "anotherFile" => "1024x768", + * ], + * "message" => [ + * "file" => "Equal resolution of file has to be 800x600", + * "anotherFile" => "Equal resolution of file has to be 1024x768", + * ], + * ] + * ) + * ); + * ``` + */ +class Equal extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'The resolution of the field :field has to be equal :resolution'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/resolution/Max.php b/src/Phalcon/validation/validator/file/resolution/Max.php new file mode 100644 index 00000000..32ca0ec1 --- /dev/null +++ b/src/Phalcon/validation/validator/file/resolution/Max.php @@ -0,0 +1,64 @@ +add( + * "file", + * new Max( + * [ + * "resolution" => "800x600", + * "message" => "Max resolution of :field is :resolution", + * "included" => true, + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Max( + * [ + * "resolution" => [ + * "file" => "800x600", + * "anotherFile" => "1024x768", + * ], + * "included" => [ + * "file" => false, + * "anotherFile" => true, + * ], + * "message" => [ + * "file" => "Max resolution of file is 800x600", + * "anotherFile" => "Max resolution of file is 1024x768", + * ], + * ] + * ) + * ); + * ``` + */ +class Max extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field exceeds the maximum resolution of :resolution'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/resolution/Min.php b/src/Phalcon/validation/validator/file/resolution/Min.php new file mode 100644 index 00000000..db1e4db0 --- /dev/null +++ b/src/Phalcon/validation/validator/file/resolution/Min.php @@ -0,0 +1,64 @@ +add( + * "file", + * new Min( + * [ + * "resolution" => "800x600", + * "message" => "Min resolution of :field is :resolution", + * "included" => true, + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Min( + * [ + * "resolution" => [ + * "file" => "800x600", + * "anotherFile" => "1024x768", + * ], + * "included" => [ + * "file" => false, + * "anotherFile" => true, + * ], + * "message" => [ + * "file" => "Min resolution of file is 800x600", + * "anotherFile" => "Min resolution of file is 1024x768", + * ], + * ] + * ) + * ); + * ``` + */ +class Min extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field can not have the minimum resolution of :resolution'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/size/Equal.php b/src/Phalcon/validation/validator/file/size/Equal.php new file mode 100644 index 00000000..2e7de623 --- /dev/null +++ b/src/Phalcon/validation/validator/file/size/Equal.php @@ -0,0 +1,64 @@ +add( + * "file", + * new Equal( + * [ + * "size" => "2M", + * "included" => true, + * "message" => ":field exceeds the equal filesize (:size)", + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Equal( + * [ + * "size" => [ + * "file" => "2M", + * "anotherFile" => "4M", + * ], + * "included" => [ + * "file" => false, + * "anotherFile" => true, + * ], + * "message" => [ + * "file" => "file does not have the rigth filesize", + * "anotherFile" => "anotherFile wrong filesize (4MB)", + * ], + * ] + * ) + * ); + * ``` + */ +class Equal extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field does not have the exact :size filesize'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/size/Max.php b/src/Phalcon/validation/validator/file/size/Max.php new file mode 100644 index 00000000..1e634676 --- /dev/null +++ b/src/Phalcon/validation/validator/file/size/Max.php @@ -0,0 +1,64 @@ +add( + * "file", + * new Max( + * [ + * "size" => "2M", + * "included" => true, + * "message" => ":field exceeds the max filesize (:size)", + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Max( + * [ + * "size" => [ + * "file" => "2M", + * "anotherFile" => "4M", + * ], + * "included" => [ + * "file" => false, + * "anotherFile" => true, + * ], + * "message" => [ + * "file" => "file exceeds the max filesize 2M", + * "anotherFile" => "anotherFile exceeds the max filesize 4M", + * ], + * ] + * ) + * ); + * ``` + */ +class Max extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field exceeds the size of :size'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/file/size/Min.php b/src/Phalcon/validation/validator/file/size/Min.php new file mode 100644 index 00000000..92d65f3f --- /dev/null +++ b/src/Phalcon/validation/validator/file/size/Min.php @@ -0,0 +1,64 @@ +add( + * "file", + * new Min( + * [ + * "size" => "2M", + * "included" => true, + * "message" => ":field exceeds the min filesize (:size)", + * ] + * ) + * ); + * + * $validator->add( + * [ + * "file", + * "anotherFile", + * ], + * new Min( + * [ + * "size" => [ + * "file" => "2M", + * "anotherFile" => "4M", + * ], + * "included" => [ + * "file" => false, + * "anotherFile" => true, + * ], + * "message" => [ + * "file" => "file exceeds the min filesize 2M", + * "anotherFile" => "anotherFile exceeds the min filesize 4M", + * ], + * ] + * ) + * ); + * ``` + */ +class Min extends \Phalcon\Validation\Validator\File\AbstractFile +{ + + protected $template = 'File :field can not have the minimum size of :size'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/stringlength/Max.php b/src/Phalcon/validation/validator/stringlength/Max.php new file mode 100644 index 00000000..fe294b5f --- /dev/null +++ b/src/Phalcon/validation/validator/stringlength/Max.php @@ -0,0 +1,66 @@ +add( + * "name_last", + * new Max( + * [ + * "max" => 50, + * "message" => "We don't like really long names", + * "included" => true + * ] + * ) + * ); + * + * $validation->add( + * [ + * "name_last", + * "name_first", + * ], + * new Max( + * [ + * "max" => [ + * "name_last" => 50, + * "name_first" => 40, + * ], + * "message" => [ + * "name_last" => "We don't like really long last names", + * "name_first" => "We don't like really long first names", + * ], + * "included" => [ + * "name_last" => false, + * "name_first" => true, + * ] + * ] + * ) + * ); + * ``` + */ +class Max extends \Phalcon\Validation\AbstractValidator +{ + + protected $template = 'Field :field must not exceed :max characters long'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +} diff --git a/src/Phalcon/validation/validator/stringlength/Min.php b/src/Phalcon/validation/validator/stringlength/Min.php new file mode 100644 index 00000000..606924c0 --- /dev/null +++ b/src/Phalcon/validation/validator/stringlength/Min.php @@ -0,0 +1,66 @@ +add( + * "name_last", + * new Min( + * [ + * "min" => 2, + * "message" => "We want more than just their initials", + * "included" => true + * ] + * ) + * ); + * + * $validation->add( + * [ + * "name_last", + * "name_first", + * ], + * new Min( + * [ + * "min" => [ + * "name_last" => 2, + * "name_first" => 4, + * ], + * "message" => [ + * "name_last" => "We don't like too short last names", + * "name_first" => "We don't like too short first names", + * ], + * "included" => [ + * "name_last" => false, + * "name_first" => true, + * ] + * ] + * ) + * ); + * ``` + */ +class Min extends \Phalcon\Validation\AbstractValidator +{ + + protected $template = 'Field :field must be at least :min characters long'; + + + /** + * Executes the validation + * + * @param \Phalcon\Validation $validation + * @param mixed $field + * @return bool + */ + public function validate(\Phalcon\Validation $validation, $field): bool {} + +}