Compare commits
47 Commits
Author | SHA1 | Date | |
---|---|---|---|
e342c7f41f | |||
7e57e5cb56 | |||
62762374e0 | |||
117deab9d8 | |||
3fbb7dc81c | |||
83a76dc8e2 | |||
6e831e2650 | |||
52de613b0f | |||
58b3b74d99 | |||
f5420ce2c0 | |||
e9118609b6 | |||
1290a567de | |||
df660676d0 | |||
3e199fc460 | |||
a58b6f1358 | |||
a439c0d2c9 | |||
ef0f2ff54d | |||
28dbf773f1 | |||
0730509096 | |||
e9333e8624 | |||
71958482c5 | |||
97f73a73e2 | |||
6a4df8373c | |||
10ec8df983 | |||
2d16baaef9 | |||
2e684cb862 | |||
f98a277986 | |||
5b83b096e5 | |||
b011d3930c | |||
ee76392d71 | |||
2a03797bfe | |||
18286ea99d | |||
697f6b81b9 | |||
8da3c1df38 | |||
07a994df83 | |||
e09ea26a3c | |||
ebfd42a88e | |||
054e6a7cdc | |||
64c1f386eb | |||
3aefbd7f27 | |||
b6f9698e59 | |||
3fd75364a1 | |||
f247253f9e | |||
c623b435e9 | |||
c32c8643ee | |||
77d3ffedb8 | |||
4f1b69d23a |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -77,3 +77,9 @@ fabric.properties
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
.idea/
|
||||
vendor/
|
||||
/tests/extensions/class.txt
|
||||
/tests/classesserialized1.txt
|
||||
/tests/classesserialized2.txt
|
||||
/tests/classesserialized3.txt
|
||||
|
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@@ -1,8 +0,0 @@
|
||||
# Файлы, игнорируемые по умолчанию
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Запросы HTTP-клиента в редакторе
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
39
.idea/anb_php_components_pack.iml
generated
39
.idea/anb_php_components_pack.iml
generated
@@ -1,39 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/sources" isTestSource="false" packagePrefix="goodboyalex\php_components_pack\" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" packagePrefix="goodboyalex\php_components_pack\tests\" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/myclabs/deep-copy" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/nikic/php-parser" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phar-io/manifest" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phar-io/version" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-code-coverage" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-file-iterator" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-invoker" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-text-template" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-timer" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/phpunit" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/cli-parser" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/comparator" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/complexity" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/diff" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/environment" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/exporter" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/global-state" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/lines-of-code" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/object-enumerator" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/object-reflector" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/recursion-context" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/type" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/version" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/staabm/side-effects-detector" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/theseer/tokenizer" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/code-unit" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/code-unit-reverse-lookup" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/anb_php_components_pack.iml" filepath="$PROJECT_DIR$/.idea/anb_php_components_pack.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
14
.idea/php-test-framework.xml
generated
14
.idea/php-test-framework.xml
generated
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="PhpTestFrameworkVersionCache">
|
||||
<tools_cache>
|
||||
<tool tool_name="PHPUnit">
|
||||
<cache>
|
||||
<versions>
|
||||
<info id="локальный\vendor/autoload.php" version="12.0" />
|
||||
</versions>
|
||||
</cache>
|
||||
</tool>
|
||||
</tools_cache>
|
||||
</component>
|
||||
</project>
|
57
.idea/php.xml
generated
57
.idea/php.xml
generated
@@ -1,57 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="MessDetectorOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PHPCSFixerOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PHPCodeSnifferOptionsConfiguration">
|
||||
<option name="highlightLevel" value="WARNING" />
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PhpIncludePathManager">
|
||||
<include_path>
|
||||
<path value="$PROJECT_DIR$/vendor/composer" />
|
||||
<path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/cli-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/staabm/side-effects-detector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/comparator" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/complexity" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/diff" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/environment" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/exporter" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/global-state" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/lines-of-code" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-enumerator" />
|
||||
<path value="$PROJECT_DIR$/vendor/nikic/php-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-reflector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/type" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-code-coverage" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-file-iterator" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-invoker" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-text-template" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/myclabs/deep-copy" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/manifest" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/code-unit" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/code-unit-reverse-lookup" />
|
||||
</include_path>
|
||||
</component>
|
||||
<component name="PhpProjectSharedConfiguration" php_language_level="8.4" />
|
||||
<component name="PhpStanOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
<component name="PhpUnit">
|
||||
<phpunit_settings>
|
||||
<PhpUnitSettings custom_loader_path="$PROJECT_DIR$/vendor/autoload.php" phpunit_phar_path="$PROJECT_DIR$/../../Internet/php/tools/phpunit/phpunit_2.phar" />
|
||||
</phpunit_settings>
|
||||
</component>
|
||||
<component name="PsalmOptionsConfiguration">
|
||||
<option name="transferred" value="true" />
|
||||
</component>
|
||||
</project>
|
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
235
LICENSE
Normal file
235
LICENSE
Normal file
@@ -0,0 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
123
|
||||
Copyright (C) 2025 babaev-an
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
@@ -6,7 +6,7 @@
|
||||
"keywords": [
|
||||
"components"
|
||||
],
|
||||
"homepage": "https://gitverse.ru/babaev-an/php_components_pack",
|
||||
"homepage": "https://git.babaev-an.ru/babaev-an/php_components_pack",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"type": "library",
|
||||
"authors": [
|
||||
@@ -16,11 +16,11 @@
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.4",
|
||||
"php": "^8.4",
|
||||
"ext-mbstring": "*"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": ">=11.5.6"
|
||||
"phpunit/phpunit": "^12.2.7"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
596
composer.lock
generated
596
composer.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +0,0 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/vendor/autoload.php';
|
||||
|
||||
require_once __DIR__ . '/sources/extensions/StringExtension.php';
|
||||
|
||||
echo \goodboyalex\php_components_pack\extensions\StringExtension::ConvertToLatin("тест");
|
29
sources/attributes/GetOnly.php
Normal file
29
sources/attributes/GetOnly.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
/**
|
||||
* Отключаю несущественные инспекции (из-за Attribute)
|
||||
*
|
||||
* @noinspection PhpMultipleClassDeclarationsInspection
|
||||
*/
|
||||
|
||||
namespace goodboyalex\php_components_pack\attributes;
|
||||
|
||||
use Attribute;
|
||||
|
||||
/**
|
||||
* Атрибут указания, что параметр является параметром только для чтения и не подлежит маппингу.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.25
|
||||
*/
|
||||
#[Attribute(flags: Attribute::TARGET_PROPERTY)]
|
||||
final readonly class GetOnly
|
||||
{
|
||||
/**
|
||||
* Конструктор
|
||||
*/
|
||||
public function __construct ()
|
||||
{
|
||||
}
|
||||
}
|
@@ -7,10 +7,12 @@
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use Closure;
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateAddTrait;
|
||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateGetTrait;
|
||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateHasTrait;
|
||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateStaticTrait;
|
||||
|
||||
/**
|
||||
* Состояние действия.
|
||||
@@ -28,9 +30,9 @@ final class ActionState implements ISerializable
|
||||
public mixed $Value;
|
||||
|
||||
/**
|
||||
* @var array $Messages Список информации
|
||||
* @var ObjectArray $Messages Список информации
|
||||
*/
|
||||
private array $Messages = [];
|
||||
private ObjectArray $Messages;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
@@ -39,218 +41,24 @@ final class ActionState implements ISerializable
|
||||
*/
|
||||
public function __construct (mixed $defValue = null)
|
||||
{
|
||||
// Присваиваю значение по умолчанию
|
||||
$this->Value = $defValue;
|
||||
|
||||
// Создаю список сообщений
|
||||
$this->Messages = new ObjectArray([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* При выводе GetStringMessages выводит только ошибки.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ERROR_ONLY (): Closure
|
||||
{
|
||||
return fn (ActionStateMessageModel $message)
|
||||
=> $message->MessageType === MessageType::Error;
|
||||
}
|
||||
// Статичные методы и константы
|
||||
use ActionStateStaticTrait;
|
||||
|
||||
/**
|
||||
* При выводе GetStringMessages выводит ошибки и предупреждения.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ERROR_AND_WARNING (): Closure
|
||||
{
|
||||
return fn (ActionStateMessageModel $message)
|
||||
=> $message->MessageType === MessageType::Error
|
||||
|| $message->MessageType === MessageType::Warning;
|
||||
}
|
||||
// Методы добавления сообщений
|
||||
use ActionStateAddTrait;
|
||||
|
||||
/**
|
||||
* При выводе GetStringMessages выводит все сообщения.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ALL (): Closure
|
||||
{
|
||||
return fn (ActionStateMessageModel $message) => true;
|
||||
}
|
||||
// Методы проверки на наличие сообщений
|
||||
use ActionStateHasTrait;
|
||||
|
||||
/**
|
||||
* Добавляет данные из другого состояния.
|
||||
*
|
||||
* @param ActionState $state Другое состояние
|
||||
* @param bool $clearAllBefore Очищать сообщения перед добавлением (true) или просто добавить к текущим (false)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddState (ActionState $state, bool $clearAllBefore = false): void
|
||||
{
|
||||
// Если нужно очистить список сообщений
|
||||
if ($clearAllBefore)
|
||||
// - то очищаю список сообщений
|
||||
$this->Clear(fn (ActionStateMessageModel $message) => true);
|
||||
|
||||
// Добавляю сообщения из другого состояния
|
||||
$this->AddRange($state->GetMessages(function (ActionStateMessageModel $message)
|
||||
{
|
||||
return true;
|
||||
}));
|
||||
|
||||
// Добавляю значение
|
||||
$this->Value = $state->Value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Очищает список сообщений, согласно условию.
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (callable $predicate): void
|
||||
{
|
||||
// Выбираю все сообщения, удовлетворяющие условию
|
||||
$list = $this->GetMessages($predicate);
|
||||
|
||||
// Удаляю их из списка
|
||||
$this->Messages = array_diff($this->Messages, $list);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбирает сообщения по условию predicate.
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
*
|
||||
* @return array Список отобранных сообщений
|
||||
*/
|
||||
public function GetMessages (callable $predicate): array
|
||||
{
|
||||
// Получаю список элементов
|
||||
$list = [];
|
||||
|
||||
// Для каждого элемента
|
||||
foreach ($this->Messages as $actionStateMessage)
|
||||
// - если он подходит под условие
|
||||
if ($predicate($actionStateMessage))
|
||||
// - добавляю его в список
|
||||
$list[] = $actionStateMessage;
|
||||
|
||||
// Возвращаю список
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет список
|
||||
*
|
||||
* @param array $messages Список сообщений
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddRange (array $messages): void
|
||||
{
|
||||
$this->Messages = array_merge($this->Messages, $messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список сообщений (параметр Message у каждого сообщения).
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
* @param string $separator Разделитель
|
||||
*
|
||||
* @return string Список сообщений
|
||||
*/
|
||||
public function GetStringMessages (callable $predicate, string $separator = '\n'): string
|
||||
{
|
||||
// Делаю выборку
|
||||
$list = $this->GetMessages($predicate);
|
||||
|
||||
// Формирую список сообщений
|
||||
$result = [];
|
||||
|
||||
// Для каждого сообщения из выборки
|
||||
foreach ($list as $message) {
|
||||
// - если оно не нужного нам класса
|
||||
if (!$message instanceof ActionStateMessageModel)
|
||||
// -- то пропускаю
|
||||
continue;
|
||||
|
||||
// - добавляю сообщение
|
||||
$result[] = $message->Message;
|
||||
}
|
||||
|
||||
// Возвращаю список
|
||||
return implode($separator, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет сообщение о критической ошибке.
|
||||
*
|
||||
* @param string $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddCritical (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessageModel(MessageType::Error, true, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавление сообщения.
|
||||
*
|
||||
* @param ActionStateMessageModel $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Add (ActionStateMessageModel $message): void
|
||||
{
|
||||
$this->Messages[] = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет сообщение об ошибке.
|
||||
*
|
||||
* @param string $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddError (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessageModel(MessageType::Error, false, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет предупреждение.
|
||||
*
|
||||
* @param string $message Сообщение.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddWarning (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessageModel(MessageType::Warning, false, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет информационное сообщение.
|
||||
*
|
||||
* @param string $message Сообщение.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddInfo (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessageModel(MessageType::Info, false, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли информационные сообщения.
|
||||
*
|
||||
* @return bool Наличие сообщений
|
||||
*/
|
||||
public function HasInfos (): bool
|
||||
{
|
||||
return $this->Count(fn (ActionStateMessageModel $message) => $message->MessageType == MessageType::Info) > 0;
|
||||
}
|
||||
// Методы получения сообщений
|
||||
use ActionStateGetTrait;
|
||||
|
||||
/**
|
||||
* Количество сообщений, удовлетворяющих условию.
|
||||
@@ -261,65 +69,7 @@ final class ActionState implements ISerializable
|
||||
*/
|
||||
public function Count (callable $predicate): int
|
||||
{
|
||||
// Получаю список сообщений
|
||||
$list = $this->GetMessages($predicate);
|
||||
|
||||
// Возвращаю результат
|
||||
return count($list);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, успешно ли завершилась операция.
|
||||
*
|
||||
* @param bool $onlyCritical Игнорировать все некритические ошибки и предупреждения (не рекомендуется!)
|
||||
*
|
||||
* @return bool Успешно ли завершилась операция.
|
||||
*/
|
||||
public function IsSuccess (bool $onlyCritical = false): bool
|
||||
{
|
||||
// Если нужно учитывать только критические ошибки
|
||||
if ($onlyCritical)
|
||||
// - то проверяю наличие критических ошибок
|
||||
return !$this->HasErrors($onlyCritical);
|
||||
|
||||
// Возвращаю результат
|
||||
return !$this->HasErrors() && !$this->HasWarnings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли ошибки.
|
||||
*
|
||||
* @param bool $onlyCritical Учитывать только критические ошибки.
|
||||
*
|
||||
* @return bool Наличие ошибок.
|
||||
*/
|
||||
public function HasErrors (bool $onlyCritical = false): bool
|
||||
{
|
||||
return $this->Count(function (ActionStateMessageModel $message) use ($onlyCritical): bool
|
||||
{
|
||||
// - сравниваю тип сообщения
|
||||
if ($message->MessageType != MessageType::Error)
|
||||
// -- если не совпадает, то возвращаю false
|
||||
return false;
|
||||
|
||||
// - если нужно выводить только критические ошибки, а сообщение не критическое
|
||||
if ($onlyCritical && !$message->IsCritical)
|
||||
// -- то возвращаю false
|
||||
return false;
|
||||
|
||||
// Возвращаю true
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли предупреждения.
|
||||
*
|
||||
* @return bool Наличие предупреждений
|
||||
*/
|
||||
public function HasWarnings (): bool
|
||||
{
|
||||
return $this->Count(fn (ActionStateMessageModel $message) => $message->MessageType == MessageType::Warning) > 0;
|
||||
return $this->Messages->Count($predicate);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -336,7 +86,7 @@ final class ActionState implements ISerializable
|
||||
$list[] = $message->Serialize();
|
||||
|
||||
// Возвращаю результат
|
||||
return serialize($list);
|
||||
return json_encode($list);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,19 +95,31 @@ final class ActionState implements ISerializable
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
// Очищаю список сообщений
|
||||
$this->Clear(fn (ActionStateMessageModel $message) => true);
|
||||
$this->Clear(self::GET_STRING_ALL());
|
||||
|
||||
// Десериализую список сообщений
|
||||
$list = unserialize($serialized);
|
||||
$list = json_decode($serialized, true);
|
||||
|
||||
// Для каждого сообщения
|
||||
foreach ($list as $messageSerialized) {
|
||||
// - создаю новое сообщение
|
||||
$message = new ActionStateMessageModel();
|
||||
$message = new ActionStateMessage();
|
||||
// - десериализую его
|
||||
$message->UnSerialize($messageSerialized);
|
||||
// - добавляю в список
|
||||
$this->Add($message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Очищает список сообщений, согласно условию.
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (callable $predicate): void
|
||||
{
|
||||
$this->Messages->Delete($predicate);
|
||||
}
|
||||
}
|
@@ -5,8 +5,10 @@ namespace goodboyalex\php_components_pack\classes;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\attributes\GetOnly;
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
use ReflectionProperty;
|
||||
use stdClass;
|
||||
use UnitEnum;
|
||||
|
||||
@@ -15,7 +17,7 @@ use UnitEnum;
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @version 1.0.1
|
||||
* @since 1.0
|
||||
*/
|
||||
final class ClassMapper
|
||||
@@ -59,6 +61,11 @@ final class ClassMapper
|
||||
// -- пропускаю
|
||||
continue;
|
||||
|
||||
// - если свойство маркируется как GetOnly
|
||||
if (self::HasGetOnlyAttributes($from, $name))
|
||||
// -- пропускаю
|
||||
continue;
|
||||
|
||||
// - если свойство не разрешено
|
||||
if (count($options['allowed']) > 0 && !in_array($name, $options['allowed']))
|
||||
// -- пропускаю
|
||||
@@ -71,6 +78,32 @@ final class ClassMapper
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли у свойства класса $class атрибуты GetOnly.
|
||||
*
|
||||
* @param object $class Объект класса.
|
||||
* @param string $propertyName Имя свойства.
|
||||
*
|
||||
* @return bool true если у свойства есть атрибут GetOnly, иначе false.
|
||||
*/
|
||||
private static function HasGetOnlyAttributes (object $class, string $propertyName): bool
|
||||
{
|
||||
// Создаем отражение свойства класса
|
||||
try {
|
||||
$reflectionProperty = new ReflectionProperty(get_class($class), $propertyName);
|
||||
}
|
||||
catch (ReflectionException) {
|
||||
// - возвращаю false, если произошла ошибка создания отражения свойства класса
|
||||
return false;
|
||||
}
|
||||
|
||||
// Получаем список атрибутов у данного свойства
|
||||
$attributes = $reflectionProperty->getAttributes(GetOnly::class);
|
||||
|
||||
// Возвращаем true, если атрибут найден, иначе false
|
||||
return !empty($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Подготавливает значения свойств класса.
|
||||
*
|
||||
@@ -211,6 +244,15 @@ final class ClassMapper
|
||||
// -- тип свойства
|
||||
$propertyType = $property->getType();
|
||||
|
||||
// - если значение является типом bool
|
||||
if ($propertyType->getName() === 'bool') {
|
||||
// -- присваиваю дату
|
||||
self::SetParameterToClass($classReflector, $key, $classObj, $value == "1");
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является классом
|
||||
if (!$propertyType->isBuiltin() && is_array($value)) {
|
||||
// -- присваиваю объект
|
||||
@@ -300,7 +342,7 @@ final class ClassMapper
|
||||
$property->setAccessible(true);
|
||||
|
||||
// Если значение null
|
||||
if ($value == null || $value == "null")
|
||||
if (!is_bool($value) && ($value == null || $value == "null"))
|
||||
// - то присваиваю значение по умолчанию
|
||||
$value = self::GetDefaults($property->getType()->getName());
|
||||
|
||||
@@ -314,18 +356,18 @@ final class ClassMapper
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает значение по умолчанию для разных типов данных.
|
||||
* Возвращает значение по умолчанию для типа $typeName.
|
||||
*
|
||||
* @param string $typeName Имя типа данных.
|
||||
* @param string $typeName Тип
|
||||
*
|
||||
* @return mixed|null Результат.
|
||||
* @return mixed Значение по умолчанию
|
||||
*/
|
||||
public static function GetDefaults (string $typeName): mixed
|
||||
{
|
||||
return match ($typeName) {
|
||||
'int' => 0,
|
||||
'float' => 0.0,
|
||||
'bool' => false,
|
||||
return match (strtolower($typeName)) {
|
||||
'int', 'integer' => 0,
|
||||
'float', 'double' => 0.0,
|
||||
'bool', 'boolean' => false,
|
||||
'string' => '',
|
||||
'array' => [],
|
||||
'object' => new stdClass(),
|
||||
|
153
sources/classes/Dictionary.php
Normal file
153
sources/classes/Dictionary.php
Normal file
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use ArrayAccess;
|
||||
use Countable;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
use goodboyalex\php_components_pack\traits\ArrayBasicTrait;
|
||||
use IteratorAggregate;
|
||||
|
||||
/**
|
||||
* Класс, описывающий словарь типа строка (ключ) -> значение любого типа (значение).
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0.3
|
||||
* @since 1.0.14
|
||||
*/
|
||||
final class Dictionary implements ArrayAccess, IteratorAggregate, Countable, ISerializable
|
||||
{
|
||||
/**
|
||||
* @var array $Container Контейнер.
|
||||
*/
|
||||
private array $Container = [];
|
||||
|
||||
// Реализация наследуемых интерфейсов и классов
|
||||
use ArrayBasicTrait;
|
||||
|
||||
/**
|
||||
* Добавление элементов в словарь.
|
||||
*
|
||||
* @param array $dictionary Ассоциативный массив вида ключ => значение, который будет добавлен в словарь.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddRange (array $dictionary): void
|
||||
{
|
||||
// Для каждого элемента массива
|
||||
foreach ($dictionary as $key => $value)
|
||||
// - добавляем его в словарь.
|
||||
$this->Add($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавление элемента в словарь.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
* @param mixed $value Хранимое значение.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Add (string $key, mixed $value): void
|
||||
{
|
||||
$this->Container[$key] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение значения по ключу.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
* @param mixed $default Значение по умолчанию, которое будет возвращено, если элемент с указанным ключом
|
||||
* отсутствует.
|
||||
*
|
||||
* @return mixed Если элемент существует, то возвращается его значение, иначе default.
|
||||
*/
|
||||
public function Get (string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->Container[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаление элемента по ключу.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Remove (string $key): void
|
||||
{
|
||||
// Если элемент с указанным ключом существует
|
||||
if ($this->Has($key))
|
||||
// - то удаляем его.
|
||||
unset($this->Container[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка наличия элемента с указанным ключом.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
*
|
||||
* @return bool Есть ли элемент с указанным ключом.
|
||||
*/
|
||||
public function Has (string $key): bool
|
||||
{
|
||||
return isset($this->Container[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистка всех элементов.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (): void
|
||||
{
|
||||
$this->Container = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function count (): int
|
||||
{
|
||||
return count($this->Container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает все ключи словаря.
|
||||
*
|
||||
* @return array Массив всех ключей словаря.
|
||||
*/
|
||||
public function Keys (): array
|
||||
{
|
||||
return array_keys($this->Container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сортирует внутренние данные по ключам.
|
||||
*
|
||||
* @param bool $descending Сортировать ли данные в обратном порядке?
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Sort (bool $descending = false): void
|
||||
{
|
||||
// Если задана сортировка по убыванию
|
||||
if ($descending)
|
||||
// - сортируем данные в обратном порядке
|
||||
krsort($this->Container);
|
||||
else
|
||||
// - иначе, стандартная сортировка по ключам в порядке возрастания
|
||||
ksort($this->Container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает все элементы словаря в виде массива.
|
||||
*
|
||||
* @return array Массив, содержащий все элементы словаря.
|
||||
*/
|
||||
public function ToArray (): array
|
||||
{
|
||||
return $this->Container;
|
||||
}
|
||||
}
|
351
sources/classes/File.php
Normal file
351
sources/classes/File.php
Normal file
@@ -0,0 +1,351 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use Exception;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
/**
|
||||
* Класс, реализующий функционал работы с файлами и выполнение операций над файлами одной командой.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0.2
|
||||
* @since 1.0.21
|
||||
*/
|
||||
final class File
|
||||
{
|
||||
/**
|
||||
* @var array Массив сообщений об ошибках при удалении директории.
|
||||
*/
|
||||
public const array REMOVE_DIRECTORY_ERROR_MESSAGES = [
|
||||
'directory_not_exist' => "Директория не существует или нет доступа на запись!",
|
||||
'error_deleting_file_or_link' => 'Ошибка удаления файла или ссылки: %s!',
|
||||
'error_deleting_directory' => 'Ошибка удаления каталога: %s. Код возврата: %d!',
|
||||
'unhandled_error' => 'Ошибка удаления директории %s: %s!'
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array Массив сообщений об ошибках при получении размера файла.
|
||||
*/
|
||||
public const array FILE_SIZE_ERROR_MESSAGES = [
|
||||
'file_not_exist' => 'Файл не существует!',
|
||||
'not_a_file' => 'Указанный путь не является файлом!',
|
||||
'cannot_get_size' => 'Не удалось получить размер файла!'
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array Массив локализации размеров файлов.
|
||||
*/
|
||||
public const array FILE_SIZE_UNITS = ['байт', 'КБ', 'МБ', 'ГБ', 'ТБ'];
|
||||
|
||||
/**
|
||||
* Получает список файлов в директории и поддиректориях, соответствующей шаблону $pattern.
|
||||
*
|
||||
* @param string $dir Родительская директория
|
||||
* @param string $pattern Шаблон имени файла
|
||||
*
|
||||
* @return false|array Список файлов или false в случае ошибки
|
||||
*/
|
||||
public static function FindFiles (string $dir, string $pattern = '*.php'): false|array
|
||||
{
|
||||
// Получаем список файлов и каталогов в текущей директории
|
||||
$files = glob("$dir/$pattern");
|
||||
|
||||
// Если произошла ошибка
|
||||
if ($files === false)
|
||||
// - то возвращаем false
|
||||
return false;
|
||||
|
||||
// Перебираем поддиректории
|
||||
foreach (glob("$dir/*", GLOB_ONLYDIR | GLOB_NOSORT) as $subDir) {
|
||||
// - если ошибка
|
||||
if ($subDir === false)
|
||||
// - то пропускаем
|
||||
continue;
|
||||
|
||||
// - рекурсивный вызов для каждой поддиректории
|
||||
$files = array_merge($files, self::FindFiles($subDir, $pattern));
|
||||
}
|
||||
|
||||
// Возвращаем список файлов
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает имя файла без пути к нему и расширения.
|
||||
*
|
||||
* @param string $fileName Полное имя файла с путем к нему.
|
||||
*
|
||||
* @return string Имя файла без пути к нему и расширения.
|
||||
*/
|
||||
public static function ExtractFileNameWithoutExtension (string $fileName): string
|
||||
{
|
||||
// Имя файла без пути к нему
|
||||
$fileNameOnly = self::ExtractFileName($fileName);
|
||||
|
||||
// Расширение файла
|
||||
$fileExtension = self::ExtractFileExtension($fileName);
|
||||
|
||||
// Возвращаем имя файла без пути к нему и расширения.
|
||||
return substr($fileNameOnly, 0, -strlen($fileExtension) - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает имя файла без пути к нему, но с расширением.
|
||||
*
|
||||
* @param string $fileName Полное имя файла с путем к нему.
|
||||
*
|
||||
* @return string Имя файла без пути к нему, но с расширением.
|
||||
*/
|
||||
public static function ExtractFileName (string $fileName): string
|
||||
{
|
||||
return basename($fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает расширение файла.
|
||||
*
|
||||
* @param string $fileName Имя файла с путем к нему.
|
||||
*
|
||||
* @return string Расширение файла.
|
||||
*/
|
||||
public static function ExtractFileExtension (string $fileName): string
|
||||
{
|
||||
|
||||
return pathinfo($fileName, PATHINFO_EXTENSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает относительный путь к файлу, относительно заданной папки
|
||||
*
|
||||
* @param string $fullPath Полный путь к файлу
|
||||
* @param string $basePath Вырезаемый путь (с начала)
|
||||
*
|
||||
* @return false|string Относительный путь к файлу
|
||||
*/
|
||||
public static function GetRelativePath (string $fullPath, string $basePath): false|string
|
||||
{
|
||||
return stripos($fullPath, $basePath) !== false ? str_replace($basePath, "", $fullPath) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаляет директорию вместе со всеми файлами и поддиректориями.
|
||||
*
|
||||
* @param string $directory Полный путь к директории.
|
||||
* @param array $errorMessages Сообщения об ошибках удаления (по умолчанию, см.
|
||||
* {@link REMOVE_DIRECTORY_ERROR_MESSAGES}).
|
||||
*
|
||||
* @return ActionState Результат удаления.
|
||||
*/
|
||||
public static function RemoveDir (string $directory,
|
||||
array $errorMessages = self::REMOVE_DIRECTORY_ERROR_MESSAGES): ActionState
|
||||
{
|
||||
// Создаю результат
|
||||
$result = new ActionState(false);
|
||||
|
||||
try {
|
||||
// Проверяем наличие директории и доступ на запись
|
||||
if (!self::DirectoryExists(directory: $directory, checkWriteAccess: true)) {
|
||||
// - если нет, то добавляем ошибку
|
||||
$result->AddError($errorMessages['directory_not_exist']);
|
||||
|
||||
// - и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Создаем рекурсивный итерационный объект для перебора всего дерева каталогов
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($directory),
|
||||
RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
|
||||
// Проходим по каждому элементу (каталогам и файлам)
|
||||
foreach ($iterator as $item) {
|
||||
// - получаем путь к файлу
|
||||
$realPath = $item->getRealPath();
|
||||
|
||||
// - если это файл или ссылка
|
||||
if ($item->isFile() || $item->isLink())
|
||||
// -- то удаляем его
|
||||
if (!@unlink($realPath)) {
|
||||
// --- если не удалось удалить, то добавляем ошибку
|
||||
$result->AddError(sprintf($errorMessages['error_deleting_file_or_link'], $realPath));
|
||||
|
||||
// --- и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
// Определение текущей операционной системы
|
||||
$os = strtolower(PHP_OS_FAMILY);
|
||||
|
||||
// Экранируем аргумент для предотвращения инъекций
|
||||
$escapedDirectory = escapeshellarg($directory);
|
||||
|
||||
// Дальнейшие действия зависят от операционной системы
|
||||
switch ($os) {
|
||||
// - для Windows
|
||||
case 'windows':
|
||||
// -- выполняем команду Windows
|
||||
exec("rd /s /q $escapedDirectory", $output, $returnCode);
|
||||
break;
|
||||
|
||||
// - для Linux/macOS
|
||||
default:
|
||||
// -- выполняем команду Linux/macOS
|
||||
exec("rm -rf $escapedDirectory", $output, $returnCode);
|
||||
break;
|
||||
}
|
||||
|
||||
// Проверяем код возврата
|
||||
if ($returnCode !== 0) {
|
||||
// - если не удалось удалить, то добавляем ошибку
|
||||
$result->AddError(sprintf($errorMessages['error_deleting_directory'], $directory, $returnCode));
|
||||
|
||||
// --- и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Если все прошло успешно (а если мы сюда попали, то все должно быть хорошо), то добавляем результат true
|
||||
$result->Value = true;
|
||||
|
||||
// - и возвращаем его
|
||||
return $result;
|
||||
}
|
||||
catch (Exception $exception) {
|
||||
// Если произошла ошибка, то добавляем ошибку
|
||||
$result->AddError(sprintf($errorMessages['unhandled_error'], $directory, $exception->getMessage()));
|
||||
|
||||
// - задаем результат false
|
||||
$result->Value = false;
|
||||
|
||||
// - и возвращаем его
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, существует ли директория.
|
||||
*
|
||||
* @param string $directory Путь к директории.
|
||||
* @param bool $checkReadAccess Проверять ли доступ на чтение директории (по умолчанию true).
|
||||
* @param bool $checkWriteAccess Проверять ли доступ на запись директории (по умолчанию false).
|
||||
*
|
||||
* @return bool Результат проверки.
|
||||
*/
|
||||
public static function DirectoryExists (string $directory, bool $checkReadAccess = true,
|
||||
bool $checkWriteAccess = false): bool
|
||||
{
|
||||
// Очищаем кэш
|
||||
clearstatcache();
|
||||
|
||||
// Проверяем, существует ли директория
|
||||
if (!file_exists($directory))
|
||||
// - если нет, то возвращаем false
|
||||
return false;
|
||||
|
||||
// Проверяем, является ли директория директорией, а не файлом
|
||||
if (!is_dir($directory))
|
||||
// - если нет, то возвращаем false
|
||||
return false;
|
||||
|
||||
// Проверяем, есть ли доступ на чтение директории
|
||||
if ($checkReadAccess && !is_readable($directory))
|
||||
// - если нет, то возвращаем false
|
||||
return false;
|
||||
|
||||
// Проверяем, есть ли доступ на запись директории
|
||||
if ($checkWriteAccess && !is_writable($directory))
|
||||
// - если нет, то возвращаем false
|
||||
return false;
|
||||
|
||||
// Если все проверки пройдены успешно, то возвращаем true
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает размер файла в байтах.
|
||||
*
|
||||
* @param string $filename Имя файла.
|
||||
* @param array $errorLocalization Массив сообщений об ошибках при получении размера файла (по умолчанию, см.
|
||||
* {@link FILE_SIZE_ERROR_MESSAGES}).
|
||||
*
|
||||
* @return ActionState Результат с размером файла в байтах.
|
||||
*/
|
||||
public static function FileSize (string $filename,
|
||||
array $errorLocalization = self::FILE_SIZE_ERROR_MESSAGES): ActionState
|
||||
{
|
||||
// Очищаем кэш
|
||||
clearstatcache();
|
||||
|
||||
// Создаём результат
|
||||
$result = new ActionState(-1);
|
||||
|
||||
// Проверяем, существует ли файл
|
||||
if (!file_exists($filename)) {
|
||||
// - если нет, то добавляем ошибку
|
||||
$result->AddError($errorLocalization['file_not_exist']);
|
||||
// - и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Проверяем, является ли $filename файлом
|
||||
if (!is_file($filename)) {
|
||||
// - если нет, то добавляем ошибку
|
||||
$result->AddError($errorLocalization['not_a_file']);
|
||||
// - и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Получаем размер файла
|
||||
$size = filesize($filename);
|
||||
|
||||
// Проверяем, получилось ли получить размер файла
|
||||
if ($size === false) {
|
||||
// - если нет, то добавляем ошибку
|
||||
$result->AddError($errorLocalization['cannot_get_size']);
|
||||
// - и возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Устанавливаем значение результата
|
||||
$result->Value = $size;
|
||||
|
||||
// Возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Преобразует размер файла в байтах в красивое строковое представление.
|
||||
*
|
||||
* @param int $fileSize Размер файла в байтах.
|
||||
* @param array $fileSizeUnits Локализованные единицы измерения размера файла (по умолчанию, см.
|
||||
* {@link FILE_SIZE_UNITS}).
|
||||
* @param string $decimalSeparator Разделитель десятичной части (по умолчанию, запятая).
|
||||
*
|
||||
* @return string Размер файла в красивом строковом представлении. Например, если размер файла составляет 1500
|
||||
* байт, вывод будет «1.46 КБ».
|
||||
*/
|
||||
public static function FileSizeToString (int $fileSize, array $fileSizeUnits = self::FILE_SIZE_UNITS,
|
||||
string $decimalSeparator = ','): string
|
||||
{
|
||||
/**
|
||||
* Вычисление степени для преобразования: берём минимум из 4 и результата округления до ближайшего целого числа
|
||||
* в меньшую сторону логарифма размера файла в байтах по основанию 1024 (это показывает, сколько раз нужно
|
||||
* разделить размер файла на 1024, чтобы получить значение в более крупных единицах измерения). Ограничение в 4
|
||||
* необходимо для того, чтобы соответствовать единице измерения ТБ (терабайт).
|
||||
*/
|
||||
$power = min(4, floor(log($fileSize, 1024)));
|
||||
|
||||
/**
|
||||
* Преобразование размера файла: размер файла делим на 1024 в степени, равной степени $power,
|
||||
* затем округляем полученное до 2 цифр после запятой.
|
||||
*/
|
||||
$size = number_format(round($fileSize / pow(1024, $power), 2), 2, $decimalSeparator);
|
||||
|
||||
// Возвращаем преобразованное значение вместе с единицей измерения
|
||||
return "$size $fileSizeUnits[$power]";
|
||||
}
|
||||
}
|
108
sources/classes/FileHash.php
Normal file
108
sources/classes/FileHash.php
Normal file
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\HashGetType;
|
||||
use goodboyalex\php_components_pack\extensions\StringExtension;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
/**
|
||||
* Класс для работы с хэшем файла или строки.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0.1
|
||||
* @since 1.0.5
|
||||
*/
|
||||
final class FileHash implements ISerializable
|
||||
{
|
||||
/**
|
||||
* @var string $Hash Хэш файла.
|
||||
*/
|
||||
private(set) string $Hash;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param string $str Хэщ, строка или имя файла.
|
||||
* @param HashGetType $hashBy Тип получения хэша.
|
||||
*/
|
||||
public function __construct (string $str = "", HashGetType $hashBy = HashGetType::ByHash)
|
||||
{
|
||||
$this->Hash = match ($hashBy) {
|
||||
HashGetType::ByString => $this->pGetHash($str),
|
||||
HashGetType::ByFile => $this->pGetFileHash($str),
|
||||
HashGetType::ByHash => $str
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение хэша файла по строке.
|
||||
*
|
||||
* @param string $str Строка.
|
||||
*
|
||||
* @return string Хэш строки.
|
||||
*/
|
||||
private function pGetHash (string $str): string
|
||||
{
|
||||
return hash('sha256', $str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение хэша файла по имени файла.
|
||||
*
|
||||
* @param string $fileName Имя файла.
|
||||
*
|
||||
* @return string Хэш файла.
|
||||
*/
|
||||
private function pGetFileHash (string $fileName): string
|
||||
{
|
||||
return hash_file('sha256', $fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сравнивает текущий хэш с хэшем <code>otherHash</code> и выдаёт <code>true</code>, если совпадают, и
|
||||
* <code>false</code>, если не совпадают.
|
||||
*
|
||||
* @param FileHash $otherHash Другой хэш.
|
||||
*
|
||||
* @return bool <code>true</code>, если совпадают, и <code>false</code>, если не совпадают.
|
||||
*/
|
||||
public function IsEqual (FileHash $otherHash): bool
|
||||
{
|
||||
return StringExtension::Compare($this->Hash, $otherHash->Hash, true) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, совпадает ли хэш с хэшем/файлом/строкой <code>str</code>.
|
||||
*
|
||||
* @param string $str Хэш, строка или имя файла.
|
||||
* @param HashGetType $hashBy Тип получения хэша.
|
||||
*
|
||||
* @return bool <code>true</code>, если совпадают, и <code>false</code>, если не совпадают.
|
||||
*/
|
||||
public function Validate (string $str, HashGetType $hashBy): bool
|
||||
{
|
||||
return match ($hashBy) {
|
||||
HashGetType::ByString => $this->pGetHash($str) == $this->Hash,
|
||||
HashGetType::ByFile => $this->pGetFileHash($str) == $this->Hash,
|
||||
HashGetType::ByHash => $str == $this->Hash,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
return serialize($this->Hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
$this->Hash = unserialize($serialized);
|
||||
}
|
||||
}
|
710
sources/classes/JsonReWriter.md
Normal file
710
sources/classes/JsonReWriter.md
Normal file
@@ -0,0 +1,710 @@
|
||||
# Описание класса JsonReWriter
|
||||
|
||||
## Информация о версии
|
||||
|
||||
Версия класса: 1.0
|
||||
|
||||
Впервые введено в пакет с версии: 1.1.0
|
||||
|
||||
Описание класса: Класс для работы с JSON-файлами.
|
||||
|
||||
## Публичные свойства и константы класса
|
||||
|
||||
В классе определены следующие свойства:
|
||||
|
||||
- `string $JsonString` - строка JSON (чтение/запись).
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Правила формирования ключей.
|
||||
|
||||
Ключ для чтения/записи данных класса формируется следующим образом: `ключ/подключ/подключ подключа` .
|
||||
|
||||
Например, если дан json-файл:
|
||||
|
||||
{
|
||||
"test": {
|
||||
"subtest": {
|
||||
"AAA": "123",
|
||||
"BBB": 1.23
|
||||
}
|
||||
},
|
||||
"test1": {
|
||||
"test": 123
|
||||
},
|
||||
"test2": {
|
||||
"test": true
|
||||
},
|
||||
"test3": {
|
||||
"test": {
|
||||
"res": "[1,2,3]"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Пусть требуется получить значение `BBB`, тогда ключ должен быть `test/subtest/BBB`.
|
||||
|
||||
### Чтение.
|
||||
|
||||
1. Создайте элемент класса `$json = new JsonReWriter ();`
|
||||
2. Если у вас требуется загрузить json из файла `$fileName`, то воспользуйтесь методом `LoadFromFile`:
|
||||
`$json->LoadFromFile($fileName);`, если же json представлен строкой `$jsonStr`, то загрузите её в свойство
|
||||
`$JsonString`: `$json->JsonString = $jsonStr;`
|
||||
3. Далее можно пользоваться любым методом для чтения `Read*`, в том числе и общим `$json->Read(...)`.
|
||||
|
||||
**Пример:**
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаю класс
|
||||
$json = new JsonReWriter();
|
||||
// Загшружаю данные из файла
|
||||
$json->LoadFromFile($fileName);
|
||||
// Получаю число
|
||||
$float = $json->ReadFloat("test/subtest/BBB", 0.2);
|
||||
|
||||
В итоге в `$float` будет `1.23`.
|
||||
|
||||
### Запись.
|
||||
|
||||
1. Создайте элемент класса `$json = new JsonReWriter ();`
|
||||
2. Далее можно пользоваться любым методом для записи `Write*`, в том числе и общим `$json->Write(...)`.
|
||||
3. Если вам требуется создать json файл с именем `$fileName`, то воспользуйтесь методом `SaveToFile`:
|
||||
`$json->SaveToFile($fileName);`, если же json должен быть представлен строкой `$jsonStr`, то загрузите её из свойства
|
||||
`$JsonString`: `$jsonStr = $json->JsonString;`
|
||||
|
||||
**Пример:**
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаю класс
|
||||
$json = new JsonReWriter();
|
||||
// Загшружаю данные из файла
|
||||
$json->LoadFromFile($fileName);
|
||||
// Получаю число
|
||||
try {
|
||||
$json->Write("test/subtest/BBB", 0.2);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
В итоге в `test/subtest/BBB` вместо `1.23` будет `0.2`.
|
||||
|
||||
## Коды ошибок JsonErrorCode
|
||||
|
||||
Ниже представлена таблица основных кодов ошибки:
|
||||
|
||||
| Ошибка | Описание | Введено с версии |
|
||||
|:-------------------:|:---------------------------------------------------------------------------:|:----------------:|
|
||||
| Unknown | Неизвестная ошибка | 1.0 |
|
||||
| None | Ошибок нет | 1.0 |
|
||||
| Depth | Достигнута максимальная глубина стека | 1.0 |
|
||||
| StateMismatch | Неверный или некорректный JSON | 1.0 |
|
||||
| CTRLChar | Ошибка управляющего символа, возможно, неверная кодировка | 1.0 |
|
||||
| Syntax | Синтаксическая ошибка | 1.0 |
|
||||
| UTF8 | Некорректные для кодировки UTF-8 символы, возможно, неверная кодировка | 1.0 |
|
||||
| Recursion | Одна или несколько зацикленных ссылок в кодируемом значении | 1.0 |
|
||||
| InfOrNan | Одно или несколько значений NAN или INF в кодируемом значении | 1.0 |
|
||||
| UnsupportedType | Передали значение с неподдерживаемым типом | 1.0 |
|
||||
| InvalidPropertyName | Имя свойства не может быть закодировано | 1.0 |
|
||||
| UTF16 | Некорректный для кодировки UTF-16 символ, возможно, некорректно закодирован | 1.0 |
|
||||
| KeyIsNotArray | Ключ не содержит вложений, хотя от него требуется обратное | 1.0 |
|
||||
| NotISerializable | Класс не реализует интерфейс ISerializable | 1.0 |
|
||||
|
||||
### Методы и функции перечисления JsonErrorCode
|
||||
|
||||
Перечисление содержит **статический метод** `static function FromLastError (): JsonErrorCode`, который получает код
|
||||
ошибки из последней JSON ошибки.
|
||||
|
||||
Например, при успешной загрузке, можем проверить ошибки:
|
||||
|
||||
$errors = JsonErrorCode::FromLastError ();
|
||||
|
||||
После того, как мы выведем `$errors`, мы получим `JsonErrorCode::None`.
|
||||
|
||||
## Исключение JsonException
|
||||
|
||||
Исключение расширяет класс `Exception`, поэтому может выбрасываться через `throw`.
|
||||
|
||||
### Свойства
|
||||
|
||||
Исключение содержит следующие свойства:
|
||||
|
||||
- `?string $JsonString` - строка JSON (или null);
|
||||
- `JsonErrorCode $ErrorCode` - код ошибки JSON;
|
||||
- `?string $ErrorMessage` - сообщение об ошибке JSON (в отличие от функции json_last_error_msg(), данная переменная при
|
||||
отсутствии ошибок выводит null, а не "No error").
|
||||
|
||||
### Методы и функции
|
||||
|
||||
#### Конструктор.
|
||||
|
||||
Конструктор принимает **3 необязательных параметра**:
|
||||
|
||||
* `?string $json` - строка JSON (по умолчанию, `null`);
|
||||
* `JsonErrorCode $errorCode` - код ошибки (по умолчанию, `JsonErrorCode::Unknown`);
|
||||
* `?string $errorMessage` - сообщение об ошибке (по умолчанию, `null`).
|
||||
|
||||
В результате создаётся новое исключение `JsonException`.
|
||||
|
||||
Пример:
|
||||
|
||||
throw new JsonException("{}", JsonErrorCode::Depth, "Пример");
|
||||
|
||||
Создаст исключение `JsonException`.
|
||||
|
||||
## Методы и функции
|
||||
|
||||
### Конструктор и деструктор.
|
||||
|
||||
Конструктор не принимает никаких параметров.
|
||||
|
||||
В результате создаётся новый класс `JsonReWriter`.
|
||||
|
||||
**Пример:**
|
||||
|
||||
// Контсуктор
|
||||
$json = new JsonReWriter ();
|
||||
// Деструктор
|
||||
unset($json);
|
||||
|
||||
Создаст и уничтожит класс `JsonReWriter`.
|
||||
|
||||
### Сохранение и загрузка из файла.
|
||||
|
||||
За сохранение и загрузку отвечают 2 метода: `SaveToFile` и `LoadFromFile`.
|
||||
|
||||
#### Сохранение в файл (метод `SaveToFile`)
|
||||
|
||||
Этот метод сохраняет содержимое JSON в файл. Он содержит **1 обязательный параметр**:
|
||||
|
||||
* `string $fileName` - имя файла на диске.
|
||||
|
||||
Метод возвращает `bool` - сохранены ли данные в файл: `true` - да, `false` - нет.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function SaveToFile (string $fileName): bool
|
||||
|
||||
**Пример:**
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Сохраняем созданный JSON файл
|
||||
$json->SaveToFile($fileName);
|
||||
|
||||
Содержимое файла `test.json` представлено далее:
|
||||
|
||||
{
|
||||
"test": {
|
||||
"subtest": {
|
||||
"AAA": "123",
|
||||
"BBB": 1.23
|
||||
}
|
||||
},
|
||||
"test1": {
|
||||
"test": 123
|
||||
},
|
||||
"test2": {
|
||||
"test": true
|
||||
},
|
||||
"test3": {
|
||||
"test": {
|
||||
"res": "[1,2,3]"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#### Загрузка файла (метод `LoadFromFile`)
|
||||
|
||||
Этот метод загружает содержимое файла в класс. Он содержит **1 обязательный параметр**:
|
||||
|
||||
* `string $fileName` - имя файла на диске.
|
||||
|
||||
Метод возвращает `bool` - загружены ли данные из файла: `true` - да, `false` - нет.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function LoadFromFile (string $fileName): bool
|
||||
|
||||
**Пример:**
|
||||
Пусть дан файл `test.json`, содержимое которого представлено далее:
|
||||
|
||||
{
|
||||
"test": {
|
||||
"subtest": {
|
||||
"AAA": "123",
|
||||
"BBB": 1.23
|
||||
}
|
||||
},
|
||||
"test1": {
|
||||
"test": 123
|
||||
},
|
||||
"test2": {
|
||||
"test": true
|
||||
},
|
||||
"test3": {
|
||||
"test": {
|
||||
"res": "[1,2,3]"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Следующий код загрузит это содержимое в класс:
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Загружаю данные
|
||||
$json->LoadFromFile($fileName);
|
||||
|
||||
### Чтение данных
|
||||
|
||||
Для чтения данных используется один общий метод `Read` и 7 его производных метода: `ReadString`, `ReadInt`, `ReadFloat`,
|
||||
`ReadBool`, `ReadArray`, `ReadObject` и `ReadSerializable`.
|
||||
|
||||
#### Метод `Read`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `mixed $default` (значение по умолчанию, задан по умолчанию в `null`).
|
||||
|
||||
Этот метод возвращает `mixed`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function Read (string $key, mixed $default = null): mixed
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Создаю класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполняю данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->Write("test3/test/res", json_encode([1, 2, 3]));
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
// Получаю значение
|
||||
$float = (float)$json->Read("test/subtest/BBB"));
|
||||
|
||||
В результате, переменная `$float` будет иметь значение `1.23`.
|
||||
|
||||
#### Метод `ReadString`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `string $default` (значение по умолчанию, задан по умолчанию в `""`).
|
||||
|
||||
Этот метод возвращает `string`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadString (string $key, string $default = ""): string
|
||||
|
||||
#### Метод `ReadInt`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `int $default` (значение по умолчанию, задан по умолчанию в `0`).
|
||||
|
||||
Этот метод возвращает `int`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadInt (string $key, int $default = 0): int
|
||||
|
||||
#### Метод `ReadFloat`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `float $default` (значение по умолчанию, задан по умолчанию в `0.0`).
|
||||
|
||||
Этот метод возвращает `float`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadFloat (string $key, float $default = 0.0): float
|
||||
|
||||
#### Метод `ReadBool`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `bool $default` (значение по умолчанию, задан по умолчанию в `false`).
|
||||
|
||||
Этот метод возвращает `bool`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadBool (string $key, bool $default = false): bool
|
||||
|
||||
#### Метод `ReadArray`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **1 обязательный параметр** `string $key` (ключ) и **1
|
||||
необязательный параметр** `array $default` (значение по умолчанию, задан по умолчанию в `[]`).
|
||||
|
||||
Этот метод возвращает `array`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadArray (string $key, array $default = []): array
|
||||
|
||||
#### Метод `ReadObject`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `object $default` (значение по умолчанию).
|
||||
|
||||
Этот метод возвращает `object`: значение ключа JSON или значение по умолчанию.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadObject (string $key, object $default): object
|
||||
|
||||
#### Метод `ReadSerializable`
|
||||
|
||||
Это метод, который читает значение ключа JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `string $serializableClassName` (имя класса, реализующего интерфейс ISerializable, с namespace).
|
||||
|
||||
Этот метод возвращает класс, реализующий интерфейс `ISerializable`.
|
||||
|
||||
**Важно!** Этот метод может выбросить исключение `JsonException`, если класс, заданный в `$serializableClassName` не
|
||||
реализует интерфейс `ISerializable`.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ReadSerializable (string $key, string $serializableClassName): ISerializable
|
||||
|
||||
**Пример,**
|
||||
|
||||
Пусть для примера, класс `Demo` из namespace `iam\namespace` реализует интерфейс `ISerializable`.
|
||||
|
||||
// Создаю класс
|
||||
$json = new JsonReWriter();
|
||||
// ... Здесь где-то загрузка данных
|
||||
// Получаю класс
|
||||
try {
|
||||
/**
|
||||
* @var Demo $unSerializableClass
|
||||
*/
|
||||
$unSerializableClass = $json->ReadSerializable("test", "iam\\namespace\\Demo");
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
В результате, переменная `$unSerializableClass` будет содержать данные класса `Demo`.
|
||||
|
||||
### Запись данных
|
||||
|
||||
Для чтения данных используется один общий метод `Write` и 3 его производных метода: `WriteArray`, `WriteObject` и
|
||||
`WriteSerializable`.
|
||||
|
||||
**Важно!** Лобой из вышеуказанных методов может выбросить исключение `JsonException`, если ключ не содержит вложений,
|
||||
хотя от него требуется обратное.
|
||||
|
||||
#### Метод `Write`
|
||||
|
||||
Это метод, который записывает значение в ключ JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `mixed $value` (записываемое значение).
|
||||
|
||||
Этот метод ничего не возвращает.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function Write (string $key, mixed $value): void
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Сохраняем созданный JSON файл
|
||||
$json->SaveToFile($fileName);
|
||||
|
||||
Содержимое файла `test.json` представлено далее:
|
||||
|
||||
{
|
||||
"test": {
|
||||
"subtest": {
|
||||
"AAA": "123",
|
||||
"BBB": 1.23
|
||||
}
|
||||
},
|
||||
"test1": {
|
||||
"test": 123
|
||||
},
|
||||
"test2": {
|
||||
"test": true
|
||||
},
|
||||
"test3": {
|
||||
"test": {
|
||||
"res": "[1,2,3]"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#### Метод `WriteArray`
|
||||
|
||||
Это метод, который записывает значение в ключ JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `array $array` (записываемое значение).
|
||||
|
||||
Этот метод ничего не возвращает.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function WriteArray (string $key, array $array): void
|
||||
|
||||
#### Метод `WriteObject`
|
||||
|
||||
Это метод, который записывает значение в ключ JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `object $value` (записываемое значение).
|
||||
|
||||
Этот метод ничего не возвращает.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function WriteObject (string $key, object $value): void
|
||||
|
||||
#### Метод `WriteSerializable`
|
||||
|
||||
Это метод, который записывает значение в ключ JSON. Он имеет **2 обязательных параметра**:
|
||||
|
||||
- `string $key` (ключ);
|
||||
- `ISerializable $serializableValue` (записываемое значение).
|
||||
|
||||
Этот метод ничего не возвращает.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function WriteSerializable (string $key, ISerializable $serializableValue): void
|
||||
|
||||
**Пример,**
|
||||
Пусть для примера, класс `Demo` из namespace `iam\namespace` реализует интерфейс `ISerializable`.
|
||||
|
||||
// Имя файла
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Создаём класс Demo
|
||||
$serializableClass = new Demo(...);
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->WriteSerializable("test", $serializableClass);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
...
|
||||
|
||||
### Работа с ключами JSON
|
||||
|
||||
Для работы с ключами JSON есть 2 метода: `IsKeyExists` и `GetKeys`.
|
||||
|
||||
#### Метод `IsKeyExists`
|
||||
|
||||
Это метод проверяем наличие ключа в JSON. Он имеет **1 обязательный параметр** - `string $key` (ключ).
|
||||
|
||||
Этот метод возвращает `bool`: `true` если ключ найден и `false` в противном случае.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function IsKeyExists (string $key): bool
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Проверяем ключи
|
||||
$check1 = $json->IsKeyExists("test/subtest/AAA");
|
||||
$check2 = $json->IsKeyExists("test/subtest/ССС");
|
||||
|
||||
В результате, `$check1` будет `true`, а `$check2` - `false`.
|
||||
|
||||
#### Метод `GetKeys`
|
||||
|
||||
Это метод получает список ключей. Он имеет **2 необязательных параметра**:
|
||||
|
||||
- `string $parentKey` (ключ родителя (или "" (установлено по умолчанию) для всех);
|
||||
- `bool $includeChildren` (нужно ли включать дочерние ключи (по умолчанию, да)).
|
||||
|
||||
Этот метод возвращает `array`: список ключей.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function GetKeys (string $parentKey = "", bool $includeChildren = true): array
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Получаем ключи
|
||||
$keys1 = $json->GetKeys("test");
|
||||
$keys2 = $json->GetKeys("test", false);
|
||||
$keys3 = $json->GetKeys();
|
||||
|
||||
В результате, `$key1` будет следующим массивом:
|
||||
|
||||
[
|
||||
"test/subtest",
|
||||
"test/subtest/AAA",
|
||||
"test/subtest/BBB"
|
||||
]
|
||||
|
||||
`$key2` будет следующим массивом:
|
||||
|
||||
[
|
||||
"subtest"
|
||||
]
|
||||
|
||||
`$key3` будет следующим массивом:
|
||||
|
||||
[
|
||||
"test",
|
||||
"test/subtest",
|
||||
"test/subtest/AAA",
|
||||
"test/subtest/BBB",
|
||||
"test1",
|
||||
"test1/test",
|
||||
"test2",
|
||||
"test2/test",
|
||||
"test3",
|
||||
"test3/test",
|
||||
"test3/test/res"
|
||||
]
|
||||
|
||||
### Удаление ключей JSON
|
||||
|
||||
Для удаления ключей JSON есть 2 метода: `DeleteKey`, который удаляет только определённый ключ и `Clear`, который удаляет
|
||||
**все ключи** из json-файла.
|
||||
|
||||
#### Метод `DeleteKey`
|
||||
|
||||
Это метод удаляет только определённый ключ в JSON. Он имеет **1 обязательный параметр** - `string $key` (ключ).
|
||||
|
||||
Этот метод возвращает `bool` - результат удаления ключа: `true` - удаление прошло успешно, `false` - произошла ошибка
|
||||
при удалении.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function DeleteKey (string $key): bool
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Получаемем ключи до удаления
|
||||
$check1 = $json->GetKeys("test/subtest");
|
||||
// Удаляем ключ
|
||||
$this->DeleteKey("test/subtest/BBB");
|
||||
// Получаемем ключи после удаления
|
||||
$check2 = $json->GetKeys("test/subtest");
|
||||
|
||||
В результате, `$check1` будет
|
||||
|
||||
[
|
||||
"test/subtest",
|
||||
"test/subtest/AAA",
|
||||
"test/subtest/BBB"
|
||||
]
|
||||
|
||||
а `$check2`:
|
||||
|
||||
[
|
||||
"test/subtest",
|
||||
"test/subtest/AAA"
|
||||
]
|
||||
|
||||
#### Метод `Clear`
|
||||
|
||||
Это метод удаляет **все ключи** из json-файла. Он не имеет никаких параметров и ничего не возвращает.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function Clear (): void
|
||||
|
||||
**Пример,**
|
||||
|
||||
// Создаём класс
|
||||
$json = new JsonReWriter();
|
||||
// Заполним данными
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
} catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
// Очищаем
|
||||
$json->Clear();
|
||||
// Получаем ключи
|
||||
$keys = $json->GetKeys();
|
||||
|
||||
В результате, `$key` будет следующим массивом:
|
||||
|
||||
[
|
||||
]
|
90
sources/classes/JsonReWriter.php
Normal file
90
sources/classes/JsonReWriter.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\JsonErrorCode;
|
||||
use goodboyalex\php_components_pack\exceptions\JsonException;
|
||||
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterDeleteTrait;
|
||||
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterKeyTrait;
|
||||
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterLoadSaveTrait;
|
||||
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterReadTrait;
|
||||
use goodboyalex\php_components_pack\traits\JsonReWriter\JsonReWriterWriteTrait;
|
||||
|
||||
/**
|
||||
* Класс для работы с JSON-файлами.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
final class JsonReWriter
|
||||
{
|
||||
/**
|
||||
* @var string $JsonString Строка JSON.
|
||||
*/
|
||||
public string $JsonString {
|
||||
get {
|
||||
// Проверка на пустоту
|
||||
if (count($this->JsonData) === 0)
|
||||
// - если массив пуст, возвращаем пустой JSON
|
||||
return '{}';
|
||||
|
||||
// Преобразую данные в JSON
|
||||
$json = json_encode($this->JsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
// Проверка на ошибки
|
||||
if (json_last_error() !== JSON_ERROR_NONE)
|
||||
// - если есть ошибки, выбрасываем исключение
|
||||
throw new JsonException(null, JsonErrorCode::FromLastError(), json_last_error_msg());
|
||||
|
||||
// Возвращаем JSON
|
||||
return $json;
|
||||
}
|
||||
set {
|
||||
// Чтение содержимого файла и преобразование JSON в объект
|
||||
$this->JsonData = json_decode($value, true);
|
||||
|
||||
// Проверка на ошибки
|
||||
if ($this->JsonData === null && json_last_error() !== JSON_ERROR_NONE)
|
||||
// - если есть ошибки, выбрасываем исключение
|
||||
throw new JsonException($value, JsonErrorCode::FromLastError(), json_last_error_msg());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @var array $JsonData Массив данных.
|
||||
*/
|
||||
private array $JsonData;
|
||||
|
||||
/**
|
||||
* Конструктор класса.
|
||||
*/
|
||||
public function __construct ()
|
||||
{
|
||||
$this->JsonData = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Деструктор класса.
|
||||
*/
|
||||
public function __destruct ()
|
||||
{
|
||||
unset($this->JsonData);
|
||||
}
|
||||
|
||||
// Подключаем методы чтения JSON
|
||||
use JsonReWriterReadTrait;
|
||||
|
||||
// Подключаем методы записи JSON
|
||||
use JsonReWriterWriteTrait;
|
||||
|
||||
// Подключаем методы сохранения и загрузки JSON
|
||||
use JsonReWriterLoadSaveTrait;
|
||||
|
||||
// Подключаем методы работы с ключами
|
||||
use JsonReWriterKeyTrait;
|
||||
|
||||
// Подключаем методы удаления данных из JSON
|
||||
use JsonReWriterDeleteTrait;
|
||||
}
|
@@ -5,10 +5,12 @@ namespace goodboyalex\php_components_pack\classes;
|
||||
use ArrayAccess;
|
||||
use Countable;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayBasicTrait;
|
||||
use goodboyalex\php_components_pack\traits\ArrayBasicTrait;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayConstantsTrait;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayLINQTrait;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySearchAndSortTrait;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySerializeExTrait;
|
||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySpecialTrait;
|
||||
use IteratorAggregate;
|
||||
|
||||
/**
|
||||
@@ -16,7 +18,7 @@ use IteratorAggregate;
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @version 1.0.6
|
||||
* @since 1.0
|
||||
*/
|
||||
final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, ISerializable
|
||||
@@ -27,7 +29,7 @@ final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, IS
|
||||
private array $Container;
|
||||
|
||||
// Реализация наследуемых интерфейсов и классов
|
||||
use ObjectArrayBasicTrait;
|
||||
use ArrayBasicTrait;
|
||||
|
||||
// Константы
|
||||
use ObjectArrayConstantsTrait;
|
||||
@@ -38,6 +40,12 @@ final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, IS
|
||||
// LINQ-подобные методы
|
||||
use ObjectArrayLINQTrait;
|
||||
|
||||
// Специальные методы
|
||||
use ObjectArraySpecialTrait;
|
||||
|
||||
// Расширенные методы для сериализации
|
||||
use ObjectArraySerializeExTrait;
|
||||
|
||||
/**
|
||||
* Конструктор класса.
|
||||
*
|
||||
@@ -47,40 +55,4 @@ final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, IS
|
||||
{
|
||||
$this->Container = $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает массив объектов, хранящихся в данном классе.
|
||||
*
|
||||
* @return array Массив объектов, хранящихся в данном классе.
|
||||
*/
|
||||
public function ToArray (): array
|
||||
{
|
||||
return $this->Container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Очищает массив объектов, хранящийся в данном классе.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (): void
|
||||
{
|
||||
// Очищаем массив
|
||||
unset($this->Container);
|
||||
|
||||
// Создаем новый массив
|
||||
$this->Container = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Объединяет массив объектов, хранящийся в данном классе, с массивом объектов, переданным в качестве параметра.
|
||||
*
|
||||
* @param array $objects Массив объектов, который будет объединен с массивом объектов, хранящимся в данном классе.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Merge (array $objects): void
|
||||
{
|
||||
$this->Container = array_merge($this->Container, $objects);
|
||||
}
|
||||
}
|
121
sources/classes/Tuple.php
Normal file
121
sources/classes/Tuple.php
Normal file
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use ArrayAccess;
|
||||
use ArrayIterator;
|
||||
use Countable;
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
use IteratorAggregate;
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
* Класс, реализующий функционал кортежей от C#.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.2
|
||||
* @since 1.0.20
|
||||
*/
|
||||
final class Tuple implements ISerializable, ArrayAccess, IteratorAggregate, Countable
|
||||
{
|
||||
/**
|
||||
* @var array Массив значений кортежа.
|
||||
*/
|
||||
private array $Values;
|
||||
|
||||
/**
|
||||
* Конструктор кортежа.
|
||||
*
|
||||
* @param mixed ...$values Значения кортежа.
|
||||
*/
|
||||
public function __construct (...$values)
|
||||
{
|
||||
$this->Values = $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
return serialize($this->Values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
$this->Values = unserialize($serialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetExists (mixed $offset): bool
|
||||
{
|
||||
return isset($this->Values[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetGet (mixed $offset): mixed
|
||||
{
|
||||
// Если ключ не является целым числом
|
||||
if (!is_int($offset))
|
||||
// - возвращаем null
|
||||
return null;
|
||||
|
||||
// Возвращаем значение кортежа по индексу
|
||||
return $this->Get($offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает значение кортежа по индексу.
|
||||
*
|
||||
* @param int $index Индекс значения.
|
||||
*
|
||||
* @return mixed Значение кортежа по индексу.
|
||||
*/
|
||||
public function Get (int $index): mixed
|
||||
{
|
||||
return $this->Values[$index] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws Exception Элементы кортежа не могут быть изменены после создания! / Tuple elements cannot be changed
|
||||
* after creation!
|
||||
*/
|
||||
public function offsetSet (mixed $offset, mixed $value): void
|
||||
{
|
||||
throw new Exception('Элементы кортежа не могут быть изменены после создания! / Tuple elements cannot be changed after creation!');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function offsetUnset (mixed $offset): void
|
||||
{
|
||||
unset($this->Values[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getIterator (): Traversable
|
||||
{
|
||||
return new ArrayIterator($this->Values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function count (): int
|
||||
{
|
||||
return count($this->Values);
|
||||
}
|
||||
}
|
183
sources/classes/TwoDimSize.php
Normal file
183
sources/classes/TwoDimSize.php
Normal file
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
/**
|
||||
* Класс, описывающий двумерный размер.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.5
|
||||
*/
|
||||
final class TwoDimSize implements ISerializable
|
||||
{
|
||||
/**
|
||||
* Разделитель частей по умолчанию.
|
||||
*/
|
||||
public const string DEFAULT_DELIMITER = ':';
|
||||
|
||||
/**
|
||||
* @var bool $NoNegativeValues Значения не должны быть отрицательными.
|
||||
*/
|
||||
public bool $NoNegativeValues = true;
|
||||
|
||||
/**
|
||||
* @var int $Width Длина (публичная)
|
||||
*/
|
||||
public int $Width {
|
||||
get {
|
||||
return $this->pWidth;
|
||||
}
|
||||
set {
|
||||
$this->pWidth = $this->NoNegativeValues ? max($value, 0) : $value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @var int $Height Ширина (публичная)
|
||||
*/
|
||||
public int $Height {
|
||||
get {
|
||||
return $this->pHeight;
|
||||
}
|
||||
set {
|
||||
$this->pHeight = $this->NoNegativeValues ? max($value, 0) : $value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @var int $pWidth Длина (приватное)
|
||||
*/
|
||||
private int $pWidth = 0;
|
||||
|
||||
/**
|
||||
* @var int $pHeight Ширина (приватное)
|
||||
*/
|
||||
private int $pHeight = 0;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param int $width Длина.
|
||||
* @param int $height Ширина.
|
||||
* @param bool $noNegativeValues Значения не должны быть отрицательными.
|
||||
*/
|
||||
public function __construct (int $width = 0, int $height = 0, bool $noNegativeValues = true)
|
||||
{
|
||||
$this->Width = $width;
|
||||
$this->Height = $height;
|
||||
$this->NoNegativeValues = $noNegativeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертация в строку (магический метод).
|
||||
*
|
||||
* @return string Строка.
|
||||
*/
|
||||
public function __toString (): string
|
||||
{
|
||||
return $this->AsString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертация в строку (расширенный метод).
|
||||
*
|
||||
* @param string $delimiter Делитель размера.
|
||||
*
|
||||
* @return string Строка.
|
||||
*/
|
||||
public function AsString (string $delimiter = self::DEFAULT_DELIMITER): string
|
||||
{
|
||||
return $this->Width . $delimiter . $this->Height;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
// Получаю строковое значение
|
||||
$str = $this->AsString("x");
|
||||
|
||||
// Добавляю допустимы ли отрицательные значения
|
||||
$str .= $this->NoNegativeValues ? "x1" : "x0";
|
||||
|
||||
// Возвращаю строку
|
||||
return $str;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
// Десериализую строку
|
||||
$result = explode("x", $serialized);
|
||||
|
||||
// Присваиваю параметры
|
||||
$this->NoNegativeValues = $result[2] === "1";
|
||||
|
||||
// Объединяю длину и ширину
|
||||
$tdSize = $result[0] . self::DEFAULT_DELIMITER . $result[1];
|
||||
|
||||
// Пытаюсь получить размер
|
||||
try {
|
||||
$result = self::Parse($tdSize, noNegativeValues: $this->NoNegativeValues);
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$result = new TwoDimSize(noNegativeValues: $this->NoNegativeValues);
|
||||
}
|
||||
|
||||
// Присваиваю длину
|
||||
$this->Width = $result->Width;
|
||||
|
||||
// Присваиваю ширину
|
||||
$this->Height = $result->Height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение размера из строки.
|
||||
*
|
||||
* @param string $str Строка.
|
||||
* @param string $delimiter Разделитель размеров.
|
||||
* @param bool $noNegativeValues Значения не должны быть отрицательными.
|
||||
*
|
||||
* @return TwoDimSize Модель размеров.
|
||||
* @throws Exception Если в строке <code>str</code> не содержится символа <code>delimiter</code> или таких
|
||||
* разделителей слишком много.
|
||||
*/
|
||||
public static function Parse (string $str, string $delimiter = self::DEFAULT_DELIMITER,
|
||||
bool $noNegativeValues = true): TwoDimSize
|
||||
{
|
||||
// Разделяю значения
|
||||
$splitSizes = explode($delimiter, $str);
|
||||
|
||||
// Проверяю, что массив имеет ровно два элемента
|
||||
if (count($splitSizes) != 2)
|
||||
throw new Exception(sprintf("Похоже, что в строке %s не содержится символа «%s» или таких разделителей слишком много!",
|
||||
$str, $delimiter));
|
||||
|
||||
// Пытаюсь получить длину
|
||||
$width = filter_var($splitSizes[0], FILTER_VALIDATE_INT);
|
||||
|
||||
// Если не удалось получить длину
|
||||
if ($width === false)
|
||||
$width = 0;
|
||||
|
||||
// Пытаюсь получить ширину
|
||||
$height = filter_var($splitSizes[1], FILTER_VALIDATE_INT);
|
||||
|
||||
// Если не удалось получить ширину
|
||||
if ($height === false)
|
||||
$height = 0;
|
||||
|
||||
// Вывожу значение
|
||||
return new TwoDimSize($width, $height, $noNegativeValues);
|
||||
}
|
||||
}
|
419
sources/classes/VersionInfo.md
Normal file
419
sources/classes/VersionInfo.md
Normal file
@@ -0,0 +1,419 @@
|
||||
# Описание класса VersionInfo
|
||||
|
||||
## Информация о версии
|
||||
|
||||
Версия класса: 1.2
|
||||
|
||||
Впервые введено в пакет с версии: 1.0.24
|
||||
Последнее обновление в версии: 1.0.27
|
||||
|
||||
Описание класса: Класс, описывающий информацию о версии.
|
||||
|
||||
## Публичные свойства и константы класса
|
||||
|
||||
В классе определены следующие константы:
|
||||
|
||||
* `array StagesNames` - имена стадий сборки.
|
||||
* `string DefaultTemplate` - шаблон вывода по умолчанию.
|
||||
|
||||
В классе определены следующе свойства:
|
||||
|
||||
* `int $Major` - мажорная версия (**только чтение**).
|
||||
* `int $Minor` - минорная версия (**только чтение**).
|
||||
* `int $Release` - номер релиза (**только чтение**).
|
||||
* `int $Build` - номер сборки (**только чтение**).
|
||||
* `VersionInfoStage $Stage` - стадия сборки (**только чтение**).
|
||||
* `int $StageNumber` - номер стадии сборки (**только чтение**).
|
||||
|
||||
## Методы и функции
|
||||
|
||||
### Конструктор.
|
||||
|
||||
Конструктор принимает **4 обязательных** и **2 дополнительных параметра**:
|
||||
|
||||
* `int $Major` - мажорная версия (**обязательный**);
|
||||
* `int $Minor` - минорная версия (**обязательный**);
|
||||
* `int $Release` - номер релиза (**обязательный**);
|
||||
* `int $Build` - номер сборки (**обязательный**);
|
||||
* `VersionInfoStage` $Stage - стадия сборки (по умолчанию, `VersionInfoStage::Undefined`);
|
||||
* `int $StageNumber` - номер стадии сборки (по умолчанию, `0`).
|
||||
|
||||
В результате создаётся новый класс `VersionInfo`.
|
||||
|
||||
Пример:
|
||||
|
||||
$version = new VersionInfo (1, 0, 0, 0, VersionInfoStage::Beta, 1);
|
||||
|
||||
Создаст класс `VersionInfo` для версии `1.0.0.0 Beta 1`.
|
||||
|
||||
### Преобразование в строку.
|
||||
|
||||
За преобразование в строку отвечает 2 метода: `ToString` и `__toString ()`.
|
||||
|
||||
#### Метод `ToString`
|
||||
|
||||
Этот метод возвращает строковое представление версии. Он содержит **2 необязательных параметра**:
|
||||
|
||||
* `string $template` - шаблон вывода (по умолчанию, `DefaultTemplate`);
|
||||
* `array $stagesNames` - имена стадий сборки (по умолчанию, `StagesNames`).
|
||||
|
||||
Метод возвращает `string` - строковое представление версии.
|
||||
|
||||
В шаблоне должны присутствовать маркеры:
|
||||
|
||||
| Маркер | Описание | Обязательный |
|
||||
|:--------------:|:--------------------|:------------:|
|
||||
| #{Major} | Мажорная версия | ДА |
|
||||
| #{Minor} | Минорная версия | ДА |
|
||||
| #{Release} | Номер релиза | ДА |
|
||||
| #{Build} | Номер сборки | ДА |
|
||||
| #{Stage} | Стадия сборки | НЕТ |
|
||||
| #{StageNumber} | Номер стадии сборки | НЕТ |
|
||||
|
||||
Эти маркеры в шаблоне заменяются на значения соответствующих свойств.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function ToString (string $template, array $stagesNames): string
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объект
|
||||
$version = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// Задаю шаблон
|
||||
$template = #{Major}.#{Minor}.#{Release} (сборка #{Build});
|
||||
|
||||
// Вывожу
|
||||
echo $version->ToString($template);
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
1.2.3 (сборка 4)
|
||||
|
||||
#### Метод `__toString`
|
||||
|
||||
Этот метод полностью аналогичен методу `ToString` с той лишь разницей, что в этом методе невозможно задать параметры
|
||||
вывода (такие, как шаблон и имена стадий). Эти параметры берутся по умолчанию.
|
||||
|
||||
Этот метод необходим для вывода корректной информации при попытке привести объект класса `VersionInfo` к типу `string`.
|
||||
|
||||
Метод возвращает `string` - строковое представление версии.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function __toString (): string
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объект
|
||||
$version = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// Вывожу
|
||||
echo $version;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
1.2.3.4 Beta 5
|
||||
|
||||
### Сравнение версий
|
||||
|
||||
Для сравнения версий используется две аналогичные друг другу (но различающиеся по способу вызова) функции: `Compare` и
|
||||
`CompareWith`.
|
||||
|
||||
#### Метод `Compare`
|
||||
|
||||
Это статический метод, который сравнивает две версии, заданные в **2 обязательных параметрах**:
|
||||
|
||||
* `VersionInfo $version1` - версия 1;
|
||||
* `VersionInfo $version2` - версия 2.
|
||||
|
||||
Этот метод возвращает `int`:
|
||||
|
||||
| version1 | version2 | Результат |
|
||||
|:---------:|:---------:|:---------:|
|
||||
| Младше | Старше | -1 |
|
||||
| Совпадает | Совпадает | 0 |
|
||||
| Старше | Младше | 1 |
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function Compare (VersionInfo $version1, VersionInfo $version2): int
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
// - $version11 младше $version12
|
||||
$version11 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
$version12 = new VersionInfo (1, 2, 3, 5, VersionInfoStage::Beta, 6);
|
||||
|
||||
// $version21 совпадает с $version22
|
||||
$version21 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
$version22 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// $version31 старше $version32
|
||||
$version31 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Stable);
|
||||
$version32 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// Сравниваю
|
||||
$verCompare1 = VersionInfo::Compare($version11, $version12);
|
||||
$verCompare2 = VersionInfo::Compare($version21, $version22);
|
||||
$verCompare3 = VersionInfo::Compare($version31, $version32);
|
||||
|
||||
// Вывожу
|
||||
echo $verCompare1 . '|' . $verCompare2 . '|' . $verCompare3;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
-1|0|1
|
||||
|
||||
#### Метод `CompareWith`
|
||||
|
||||
Этот метод полностью аналогичен методу `Compare`. Он отличается лишь только тем, что **не статичен** и вызывается из
|
||||
ранее созданного экземпляра класса. Он сравнивает текущую версию с переданной. Этот метод имеет только **1 обязательный
|
||||
параметр**: `VersionInfo $version` - переданная версия.
|
||||
|
||||
Этот метод возвращает `int`: `1`, если текущая версия старше переданной, `0`, если совпадает и `-1`, если текущая версия
|
||||
младше переданной.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function CompareWith (VersionInfo $version): int
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
// - $version11 младше $version12
|
||||
$version11 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
$version12 = new VersionInfo (1, 2, 3, 5, VersionInfoStage::Beta, 6);
|
||||
|
||||
// $version21 совпадает с $version22
|
||||
$version21 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
$version22 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// $version31 старше $version32
|
||||
$version31 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Stable);
|
||||
$version32 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
|
||||
// Сравниваю
|
||||
$verCompare1 = $version11->CompareWith($version12);
|
||||
$verCompare2 = $version21->CompareWith($version22);
|
||||
$verCompare3 = $version31->CompareWith($version32);
|
||||
|
||||
// Вывожу
|
||||
echo $verCompare1 . '|' . $verCompare2 . '|' . $verCompare3;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
-1|0|1
|
||||
|
||||
#### Метод `CompareWithRange`
|
||||
|
||||
Введено в версии `1.0.27`.
|
||||
|
||||
Это метод, который проверяет, находится ли текущая версия в заданном диапазоне, указанном в **2 необязательных
|
||||
параметрах**:
|
||||
|
||||
* `VersionInfo (или null) $left` - левая граница, по умолчанию, `null`;
|
||||
* `VersionInfo (или null) $right` - правая граница, по умолчанию, `null`.
|
||||
|
||||
В случае, если будет передан `null` вместо левой границы, то метод создаст класс `VersionInfo` с минимально возможной
|
||||
версией `0.0.0.0 PreAlpha 0`, а вместо правой - `VersionInfo` с максимально возможной версией
|
||||
`9223372036854775807.9223372036854775807.9223372036854775807.9223372036854775807 Stable` (здесь `9223372036854775807` -
|
||||
максимальное число INT по умолчанию - у вас может быть другое).
|
||||
|
||||
Границы могут совпадать, тогда поведение будет совпадать с методом `CompareWith` (при условии, что границы включены).
|
||||
Кроме того, работает защита "от дурака" и если границы перепутаны, то метод автоматически поменяет их местами.
|
||||
|
||||
**3-й необязательный параметр** отвечает за параметры сравнения. Это `ObjectArray` из перечисления
|
||||
`VersionCompareRangeOption`, который может содержать следующие настройки:
|
||||
|
||||
| Настройка | Описание | Включена по умолчанию |
|
||||
|:-------------------:|:-------------------------------------:|:---------------------:|
|
||||
| LeftBorderIncluded | Включена ли левая граница в диапазон | ДА |
|
||||
| RightBorderIncluded | Включена ли правая граница в диапазон | ДА |
|
||||
|
||||
Этот метод возвращает `int`:
|
||||
|
||||
| Текущая версия | Результат |
|
||||
|:---------------------------------:|:---------:|
|
||||
| Младше диапазона | -1 |
|
||||
| Внутри диапазона (или на границе) | 0 |
|
||||
| Старше диапазона | 1 |
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public function CompareWithRange (?VersionInfo $left = null, ?VersionInfo $right = null, ?ObjectArray $options = null): int
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
// - 1.2.3.4 Beta 1
|
||||
$versionInfo1 = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
|
||||
// - 1.1.3.4 Alpha 2
|
||||
$versionInfo2 = new VersionInfo(1, 1, 3, 4, VersionInfoStage::Alpha, 2);
|
||||
|
||||
// - 1.1.1.1 Alpha 2
|
||||
$versionInfo3 = new VersionInfo(1, 1, 1, 1, VersionInfoStage::Alpha, 2);
|
||||
|
||||
// - 5.5.5.5 Stable
|
||||
$versionInfo4 = new VersionInfo(5, 5, 5, 5, VersionInfoStage::Stable);
|
||||
|
||||
// Сравниваю
|
||||
echo "Для начала простое сравнение: ";
|
||||
$ver1d1 = $versionInfo1->CompareWithRange($versionInfo3, $versionInfo4);
|
||||
$ver1d2 = $versionInfo2->CompareWithRange($versionInfo1, $versionInfo4);
|
||||
$ver1d2 = $versionInfo4->CompareWithRange($versionInfo2, $versionInfo1);
|
||||
echo "$ver1d1|$ver1d2|$ver1d3 \r\n"
|
||||
|
||||
echo "Немного перепутаем границы =) ";
|
||||
$ver2d1 = $versionInfo4->CompareWithRange($versionInfo1, $versionInfo2);
|
||||
echo "И получим: $ver2d1\r\n";
|
||||
|
||||
echo "А теперь с границами!\r\n";
|
||||
echo "- значение равно левой границе: ";
|
||||
$ver3d1 = $versionInfo2->CompareWithRange($versionInfo2, $versionInfo1);
|
||||
echo " $ver3d1\r\n";
|
||||
echo "- значение равно правой границе: ";
|
||||
$ver3d2 = $versionInfo1->CompareWithRange($versionInfo2, $versionInfo1);
|
||||
echo " $ver3d2\r\n";
|
||||
echo "- а теперь с выключением границ:\r\n";
|
||||
echo "-- для левой: ";
|
||||
$ver3d3 = $versionInfo2->CompareWithRange($versionInfo2, $versionInfo1, $optionNotBorder);
|
||||
echo " $ver3d3\r\n";
|
||||
echo "-- для правой: ";
|
||||
$ver3d4 = $versionInfo1->CompareWithRange($versionInfo2, $versionInfo1, $optionNotBorder);
|
||||
echo " $ver3d4\r\n";
|
||||
echo "А что если границы равны и значение равно?\r\n";
|
||||
echo "- для включённых границ: ";
|
||||
$ver4d1 = $versionInfo1->CompareWithRange($versionInfo1, $versionInfo1);
|
||||
echo " $ver4d1\r\n";
|
||||
echo "- для выключённых границ: ";
|
||||
$ver4d2 = $versionInfo1->CompareWithRange($versionInfo1, $versionInfo1, $optionNotBorder);
|
||||
echo " $ver4d2";
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
Для начала простое сравнение: 0|-1|1
|
||||
Немного перепутаем границы =) И получим: 1
|
||||
А теперь с границами!
|
||||
- значение равно левой границе: 0
|
||||
- значение равно правой границе: 0
|
||||
- а теперь с выключением границ:
|
||||
-- для левой: -1
|
||||
-- для правой: 1
|
||||
А что если границы равны и значение равно?
|
||||
- для включённых границ: 0
|
||||
- для выключённых границ: -1
|
||||
|
||||
### Парсинг версий
|
||||
|
||||
Для преобразования строки с версией в объект `VersionInfo` используется статичный метод `Parse`.
|
||||
|
||||
Он требует **1 обязательный параметр** и **1 необязательный**:
|
||||
|
||||
* `string $version` - строка с версией (она должна быть в формате
|
||||
`#{Major}.#{Minor}.#{Release}.#{Build} #{Stage} #{StageNumber}`, причём `#{Stage}` и `#{StageNumber}` можно не
|
||||
указывать);
|
||||
* `array $stagesNames` - имена стадий сборки (по умолчанию, `StagesNames`).
|
||||
|
||||
Этот метод возвращает объект {@link VersionInfo} с данными о версии или `new VersionInfo(0, 0, 0, 0)` в случае ошибки.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function Parse (string $version, array $stagesNames = self::StagesNames): VersionInfo
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю текст
|
||||
$verText = '1.2.3.4 Beta 2';
|
||||
|
||||
// Преобразую
|
||||
$version = VersionInfo::Parse($verText);
|
||||
|
||||
// Вывожу
|
||||
echo $version;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
1.2.3.4 Beta 2
|
||||
|
||||
### Вспомогательные методы
|
||||
|
||||
#### Метод `IsNotUndefinedOrStable`
|
||||
|
||||
Этот **статический** метод проверяет, является ли версия в неопределённой стадии или уже релизом.
|
||||
|
||||
Он имеет только **1 обязательный параметр**: `VersionInfoStage $versionStage` - стадия сборки.
|
||||
|
||||
Этот метод возвращает `bool`: `true`, если стадия сборки определена и не является релизом и `false` в противном случае.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function IsNotUndefinedOrStable (VersionInfoStage $versionStage): bool
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
$version1 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Undefined, 5);
|
||||
$version2 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Beta, 5);
|
||||
$version3 = new VersionInfo (1, 2, 3, 4, VersionInfoStage::Stable);
|
||||
|
||||
// Сравниваю
|
||||
$res1 = VersionInfo::IsNotUndefinedOrStabl($version1->Stage);
|
||||
$res2 = VersionInfo::IsNotUndefinedOrStabl($version2->Stage);
|
||||
$res3 = VersionInfo::IsNotUndefinedOrStabl($version3->Stage);
|
||||
|
||||
// Вывожу
|
||||
echo $res1 . '|' . $res2 . '|' . $res3;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
false|true|false
|
||||
|
||||
#### Метод `MinVersion`
|
||||
|
||||
Введено в версии `1.0.28`.
|
||||
|
||||
Этот **статический** метод **без параметров** возвращает минимальную версию (объект класса `VersionInfo`).
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function MinVersion (): VersionInfo
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
$version = VersionInfo::MinVersion();
|
||||
|
||||
// Вывожу
|
||||
echo $version;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
0.0.0.0 PreAlpha 0
|
||||
|
||||
#### Метод `MaxVersion`
|
||||
|
||||
Введено в версии `1.0.28`.
|
||||
|
||||
Этот **статический** метод **без параметров** возвращает максимальную версию (объект класса `VersionInfo`).
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function MaxVersion (): VersionInfo
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаю объекты
|
||||
$version = VersionInfo::MaxVersion();
|
||||
|
||||
// В этом примере считается, что константа PHP_INT_MAX равна 9223372036854775807
|
||||
|
||||
// Вывожу
|
||||
echo $version;
|
||||
|
||||
В результате на экране появится:
|
||||
|
||||
9223372036854775807.9223372036854775807.9223372036854775807.9223372036854775807
|
391
sources/classes/VersionInfo.php
Normal file
391
sources/classes/VersionInfo.php
Normal file
@@ -0,0 +1,391 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\VersionCompareRangeOption;
|
||||
use goodboyalex\php_components_pack\enums\VersionInfoStage;
|
||||
use goodboyalex\php_components_pack\extensions\StringExtension;
|
||||
|
||||
/**
|
||||
* Класс, описывающий информацию о версии.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.2
|
||||
* @since 1.0.24
|
||||
*/
|
||||
final class VersionInfo
|
||||
{
|
||||
/**
|
||||
* @var array $StagesNames Имена стадий сборки.
|
||||
*/
|
||||
public const array StagesNames = [
|
||||
VersionInfoStage::PreAlpha->value => 'PreAlpha',
|
||||
VersionInfoStage::Alpha->value => 'Alpha',
|
||||
VersionInfoStage::Beta->value => 'Beta',
|
||||
VersionInfoStage::ReleaseCandidate->value => 'rc',
|
||||
VersionInfoStage::Stable->value => 'Stable'
|
||||
];
|
||||
|
||||
/**
|
||||
* @var string $DefaultTemplate Шаблон вывода по умолчанию.
|
||||
*/
|
||||
public const string DefaultTemplate = '#{Major}.#{Minor}.#{Release}.#{Build} #{Stage} #{StageNumber}';
|
||||
|
||||
/**
|
||||
* @var int $Major Мажорная версия.
|
||||
*/
|
||||
private(set) int $Major = 0;
|
||||
|
||||
/**
|
||||
* @var int $Minor Минорная версия.
|
||||
*/
|
||||
private(set) int $Minor = 0;
|
||||
|
||||
/**
|
||||
* @var int $Release Номер релиза.
|
||||
*/
|
||||
private(set) int $Release = 0;
|
||||
|
||||
/**
|
||||
* @var int $Build Номер сборки.
|
||||
*/
|
||||
private(set) int $Build = 0;
|
||||
|
||||
/**
|
||||
* @var VersionInfoStage $Stage Стадия сборки.
|
||||
*/
|
||||
private(set) VersionInfoStage $Stage = VersionInfoStage::Undefined;
|
||||
|
||||
/**
|
||||
* @var int $StageNumber Номер стадии сборки.
|
||||
*/
|
||||
private(set) int $StageNumber = 0;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param int $Major Мажорная версия.
|
||||
* @param int $Minor Минорная версия.
|
||||
* @param int $Release Номер релиза.
|
||||
* @param int $Build Номер сборки.
|
||||
* @param VersionInfoStage $Stage Стадия сборки.
|
||||
* @param int $StageNumber Номер стадии сборки.
|
||||
*/
|
||||
public function __construct (int $Major, int $Minor, int $Release, int $Build,
|
||||
VersionInfoStage $Stage = VersionInfoStage::Undefined, int $StageNumber = 0)
|
||||
{
|
||||
$this->Major = $Major;
|
||||
$this->Minor = $Minor;
|
||||
$this->Release = $Release;
|
||||
$this->Build = $Build;
|
||||
$this->Stage = $Stage;
|
||||
$this->StageNumber = $StageNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сравнивает две версии.
|
||||
*
|
||||
* @param VersionInfo $version1 Версия 1.
|
||||
* @param VersionInfo $version2 Версия 2.
|
||||
*
|
||||
* @return int Возвращает 1, если версия 1 больше версии 2, 0, если равны, -1, если версия 1 меньше версии 2.
|
||||
*/
|
||||
public static function Compare (VersionInfo $version1, VersionInfo $version2): int
|
||||
{
|
||||
return $version1->CompareWith($version2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сравнивает текущую версию с переданной.
|
||||
*
|
||||
* @param VersionInfo $version Переданная версия.
|
||||
*
|
||||
* @return int Возвращает 1, если текущая версия больше переданной, 0, если равны, -1, если текущая версия меньше
|
||||
* переданной.
|
||||
*/
|
||||
public function CompareWith (VersionInfo $version): int
|
||||
{
|
||||
// Задаем шаблон вывода
|
||||
$toStringTemplate = '#{Major}.#{Minor}.#{Release}.#{Build}';
|
||||
|
||||
// Сначала сравним числа (мажорную, минорную версии, номер релиза и сборки):
|
||||
$compareResult = version_compare(
|
||||
$this->ToString($toStringTemplate),
|
||||
$version->ToString($toStringTemplate)
|
||||
);
|
||||
|
||||
// Если численные части совпадают, проверяем стадии сборки
|
||||
if ($compareResult === 0) {
|
||||
// - особый случай: стабильная версия всегда больше любых промежуточных стадий
|
||||
if ($this->Stage === VersionInfoStage::Stable && self::IsNotUndefinedOrStable($version->Stage))
|
||||
// - считаем нашу старшей
|
||||
return 1;
|
||||
|
||||
// - особый случай: если наша версия не stable, а другая stable
|
||||
if ($version->Stage === VersionInfoStage::Stable && self::IsNotUndefinedOrStable($this->Stage))
|
||||
// - считаем нашу младшей
|
||||
return -1;
|
||||
|
||||
// - преобразуем стадии в целые числа для прямого сравнения
|
||||
$currentStageValue = $this->Stage->ToInt();
|
||||
$otherStageValue = $version->Stage->ToInt();
|
||||
|
||||
// - если стадии отличаются
|
||||
if ($currentStageValue !== $otherStageValue)
|
||||
// - сравниваем их
|
||||
return $currentStageValue <=> $otherStageValue;
|
||||
|
||||
// - если стадии одинаковые
|
||||
if (self::IsNotUndefinedOrStable($this->Stage) && self::IsNotUndefinedOrStable($version->Stage)
|
||||
&& $this->StageNumber !== $version->StageNumber)
|
||||
return $this->StageNumber <=> $version->StageNumber;
|
||||
|
||||
// - если все совпадает, то вернём 0
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Возврат результата сравнения
|
||||
return $compareResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает строковое представление версии.
|
||||
*
|
||||
* @param string $template Шаблон вывода. В шаблоне маркеры #{Major}, #{Minor}, #{Release}, #{Build}, #{Stage} и
|
||||
* #{StageNumber} заменяются на значения соответствующих свойств. По умолчанию используется
|
||||
* {@link DefaultTemplate}.
|
||||
* @param array $stagesNames Имена стадий сборки (по умолчанию из константы {@link StagesNames}).
|
||||
*
|
||||
* @return string Строковое представление версии.
|
||||
*/
|
||||
public function ToString (string $template = self::DefaultTemplate, array $stagesNames = self::StagesNames): string
|
||||
{
|
||||
// Получаем строковое представление стадии сборки
|
||||
$stage = match ($this->Stage) {
|
||||
// - для неопределенной стадии сборки и релиза возвращаем пустую строку
|
||||
VersionInfoStage::Undefined, VersionInfoStage::Stable => '',
|
||||
|
||||
// - для остальных стадий сборки возвращаем строковое представление стадии сборки
|
||||
VersionInfoStage::PreAlpha => $stagesNames[VersionInfoStage::PreAlpha->value],
|
||||
VersionInfoStage::Alpha => $stagesNames[VersionInfoStage::Alpha->value],
|
||||
VersionInfoStage::Beta => $stagesNames[VersionInfoStage::Beta->value],
|
||||
VersionInfoStage::ReleaseCandidate => $stagesNames[VersionInfoStage::ReleaseCandidate->value]
|
||||
};
|
||||
|
||||
// Возвращаем строковое представление номера стадии сборки, если конечно стадия определена и она не релиз
|
||||
// и номер сборки должен быть задан (больше 0)
|
||||
$stageNum = self::IsNotUndefinedOrStable($this->Stage) && $this->StageNumber > 0
|
||||
? "$this->StageNumber" : '';
|
||||
|
||||
// Создаём массив для замены
|
||||
$replaceData = [
|
||||
'#{Major}' => "$this->Major",
|
||||
'#{Minor}' => "$this->Minor",
|
||||
'#{Release}' => "$this->Release",
|
||||
'#{Build}' => "$this->Build",
|
||||
'#{Stage}' => $stage,
|
||||
'#{StageNumber}' => $stageNum
|
||||
];
|
||||
|
||||
// Заменяем все в шаблоне
|
||||
$result = StringExtension::ReplaceAll($replaceData, $template);
|
||||
|
||||
// Возвращаем результат, удаляя лишние пробелы в конце
|
||||
return rtrim($result, ' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, является ли версия неопределённой или релизом.
|
||||
*
|
||||
* @param VersionInfoStage $versionStage Стадия сборки.
|
||||
*
|
||||
* @return bool Возвращает true, если стадия сборки определена и не является релизом.
|
||||
*/
|
||||
public static function IsNotUndefinedOrStable (VersionInfoStage $versionStage): bool
|
||||
{
|
||||
return $versionStage !== VersionInfoStage::Undefined && $versionStage !== VersionInfoStage::Stable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Преобразует строку с версией в объект {@link VersionInfo}.
|
||||
*
|
||||
* @param string $version Строка с версией (она должна быть в формате {@link DefaultTemplate}).
|
||||
* @param array $stagesNames Имена стадий сборки (по умолчанию из константы {@link StagesNames}).
|
||||
*
|
||||
* @return VersionInfo Возвращает объект {@link VersionInfo} с данными о версии.
|
||||
*/
|
||||
public static function Parse (string $version, array $stagesNames = self::StagesNames): VersionInfo
|
||||
{
|
||||
// Убираем пробелы в начале и конце строки
|
||||
$version = trim($version);
|
||||
|
||||
// Разбиваем строку на части по пробелам (1 часть - основная - мажор, минор, релиз, сборка,
|
||||
// 2 часть - стадия и 3 - номер стадии)
|
||||
$versionParts = explode(' ', $version);
|
||||
|
||||
// Проверяем, что строка содержит хотя бы 1 часть
|
||||
if (count($versionParts) < 1)
|
||||
// - если нет, то возвращаем пустую версию
|
||||
return new VersionInfo(0, 0, 0, 0);
|
||||
|
||||
// Составим регулярное выражение для парсинга базовой информации о версии
|
||||
$pattern = '/^(\d+)\.(\d+)\.(\d+)\.(\d+)/';
|
||||
|
||||
// Парсим базовую информацию о версии
|
||||
if (!preg_match($pattern, $versionParts[0], $matches))
|
||||
// - если не удалось, то возвращаем пустую версию
|
||||
return new VersionInfo(0, 0, 0, 0);
|
||||
|
||||
// Проверяем, что найдены все 4 части
|
||||
if (!$matches || count($matches) < 5)
|
||||
// - если нет, то возвращаем пустую версию
|
||||
return new VersionInfo(0, 0, 0, 0);
|
||||
|
||||
// Получаем значения
|
||||
[, $major, $minor, $release, $build] = $matches;
|
||||
|
||||
// Парсим обязательные цифры
|
||||
// - мажорная версия
|
||||
$major = intval($major);
|
||||
// - минорная версия
|
||||
$minor = intval($minor);
|
||||
// - номер релиза
|
||||
$release = intval($release);
|
||||
// - номер сборки
|
||||
$build = intval($build);
|
||||
|
||||
// Если частей версии больше 1
|
||||
if (count($versionParts) > 1) {
|
||||
// - получаем массив для перевода строковых имен стадий в числа
|
||||
$stageEnumMap = array_flip($stagesNames);
|
||||
|
||||
// - получаем стадию
|
||||
$stage = VersionInfoStage::FromInt(intval($stageEnumMap[$versionParts[1]] ?? 0));
|
||||
|
||||
// - если стадия определена и не релиз, и кроме того, есть номер стадии
|
||||
if (self::IsNotUndefinedOrStable($stage) && count($versionParts) > 2)
|
||||
// -- получаем номер стадии
|
||||
$stageNumber = intval($versionParts[2]);
|
||||
else
|
||||
// -- иначе, устанавливаем номер стадии 0
|
||||
$stageNumber = 0;
|
||||
}
|
||||
else {
|
||||
// - иначе, устанавливаем стадию неопределённой
|
||||
$stage = VersionInfoStage::Undefined;
|
||||
// - и номер стадии 0
|
||||
$stageNumber = 0;
|
||||
}
|
||||
|
||||
// Создание объекта VersionInfo
|
||||
return new VersionInfo($major, $minor, $release, $build, $stage, $stageNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выводит строковое представление версии (упрощённая версия ToString() с шаблоном по умолчанию, необходимая для
|
||||
* вывода при попытке привести объект к типу string).
|
||||
*
|
||||
* @return string Строковое представление версии.
|
||||
*/
|
||||
public function __toString (): string
|
||||
{
|
||||
// Получаем строковое представление версии и возвращаем его
|
||||
return $this->ToString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, находится ли текущая версия в заданном диапазоне.
|
||||
*
|
||||
* @param VersionInfo|null $left Левая граница диапазона или null, если граница не задана (будет использована
|
||||
* минимальная версия).
|
||||
* @param VersionInfo|null $right Правая граница диапазона или null, если граница не задана (будет использована
|
||||
* максимальная версия).
|
||||
* @param ObjectArray|null $options Опции проверки (по умолчанию массив, который разрешает включать границы).
|
||||
*
|
||||
* @return int Возвращает 1, если текущая версия старше интервала, 0, если находится в интервале, -1, если текущая
|
||||
* версия младше интервала.
|
||||
*
|
||||
* @version 1.1
|
||||
* @since 1.0.27
|
||||
*/
|
||||
public function CompareWithRange (?VersionInfo $left = null, ?VersionInfo $right = null,
|
||||
?ObjectArray $options = null): int
|
||||
{
|
||||
// Подготавливаем опции, если они не переданы
|
||||
$options ??= new ObjectArray([
|
||||
VersionCompareRangeOption::LeftBorderIncluded,
|
||||
VersionCompareRangeOption::RightBorderIncluded
|
||||
]);
|
||||
|
||||
// Устанавливаем левую границу
|
||||
$leftBorder = $left ?? self::MinVersion();
|
||||
|
||||
// Устанавливаем правую границу
|
||||
$rightBorder = $right ?? self::MaxVersion();
|
||||
|
||||
// Проверяем, что границы не перепутаны
|
||||
if ($leftBorder->CompareWith($rightBorder) == 0)
|
||||
// - если границы перепутаны, то меняем их местами
|
||||
[$leftBorder, $rightBorder] = [$rightBorder, $leftBorder];
|
||||
|
||||
// Проверяем текущую версию относительно границ
|
||||
$compareLeft = $this->CompareWith($leftBorder);
|
||||
$compareRight = $this->CompareWith($rightBorder);
|
||||
|
||||
// Проверяем, что границы включены
|
||||
// - левая
|
||||
$leftBorderIncluded = $options->IsExist(fn (VersionCompareRangeOption $option)
|
||||
=> $option === VersionCompareRangeOption::LeftBorderIncluded);
|
||||
// - правая
|
||||
$rightBorderIncluded = $options->IsExist(fn (VersionCompareRangeOption $option)
|
||||
=> $option === VersionCompareRangeOption::RightBorderIncluded);
|
||||
|
||||
// Проверяем включение границ
|
||||
$isInInterval =
|
||||
(
|
||||
($compareLeft >= 0 && $leftBorderIncluded)
|
||||
|| ($compareLeft > 0)
|
||||
)
|
||||
&& (
|
||||
($compareRight <= 0 && $rightBorderIncluded)
|
||||
|| ($compareRight < 0)
|
||||
);
|
||||
|
||||
// Итоговая обработка результатов
|
||||
if ($isInInterval)
|
||||
// - версия в пределах диапазона
|
||||
return 0;
|
||||
else // - версия не в пределах диапазона, и если она младше левой границы (или равна ей при не включении границы)
|
||||
if ($compareLeft <= 0)
|
||||
// -- то возвращаем -1
|
||||
return -1;
|
||||
else
|
||||
// -- в противном случае, версия старше правой границы (или равна ей при не включении границы)
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает минимальную версию.
|
||||
*
|
||||
* @return VersionInfo Минимальная версия.
|
||||
*
|
||||
* @since 1.0.28
|
||||
*/
|
||||
public static function MinVersion (): VersionInfo
|
||||
{
|
||||
return new VersionInfo(0, 0, 0, 0, VersionInfoStage::PreAlpha, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает максимальную версию.
|
||||
*
|
||||
* @return VersionInfo Максимальная версия.
|
||||
*
|
||||
* @since 1.0.28
|
||||
*/
|
||||
public static function MaxVersion (): VersionInfo
|
||||
{
|
||||
return new VersionInfo(PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MAX, VersionInfoStage::Stable);
|
||||
}
|
||||
}
|
34
sources/enums/HashGetType.php
Normal file
34
sources/enums/HashGetType.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление типов получения хэша.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.1
|
||||
* @since 1.0.5
|
||||
*/
|
||||
enum HashGetType: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* По строке хэша.
|
||||
*/
|
||||
case ByHash = 0;
|
||||
|
||||
/**
|
||||
* По строке.
|
||||
*/
|
||||
case ByString = 1;
|
||||
|
||||
/**
|
||||
* По файлу.
|
||||
*/
|
||||
case ByFile = 2;
|
||||
}
|
108
sources/enums/JsonErrorCode.php
Normal file
108
sources/enums/JsonErrorCode.php
Normal file
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление известных ошибок при работе с JSON файлами.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
enum JsonErrorCode: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Неизвестная ошибка.
|
||||
*/
|
||||
case Unknown = -1;
|
||||
|
||||
/**
|
||||
* Ошибок нет.
|
||||
*/
|
||||
case None = 0;
|
||||
|
||||
/**
|
||||
* Достигнута максимальная глубина стека.
|
||||
*/
|
||||
case Depth = 1;
|
||||
|
||||
/**
|
||||
* Неверный или некорректный JSON.
|
||||
*/
|
||||
case StateMismatch = 2;
|
||||
|
||||
/**
|
||||
* Ошибка управляющего символа, возможно, неверная кодировка.
|
||||
*/
|
||||
case CTRLChar = 3;
|
||||
|
||||
/**
|
||||
* Синтаксическая ошибка.
|
||||
*/
|
||||
case Syntax = 4;
|
||||
|
||||
/**
|
||||
* Некорректные для кодировки UTF-8 символы, возможно, неверная кодировка.
|
||||
*/
|
||||
case UTF8 = 5;
|
||||
|
||||
/**
|
||||
* Одна или несколько зацикленных ссылок в кодируемом значении.
|
||||
*/
|
||||
case Recursion = 6;
|
||||
|
||||
/**
|
||||
* Одно или несколько значений NAN или INF в кодируемом значении.
|
||||
*/
|
||||
case InfOrNan = 7;
|
||||
|
||||
/**
|
||||
* Передали значение с неподдерживаемым типом.
|
||||
*/
|
||||
case UnsupportedType = 8;
|
||||
|
||||
/**
|
||||
* Имя свойства не может быть закодировано.
|
||||
*/
|
||||
case InvalidPropertyName = 9;
|
||||
|
||||
/**
|
||||
* Некорректный для кодировки UTF-16 символ, возможно, некорректно закодирован.
|
||||
*/
|
||||
case UTF16 = 10;
|
||||
|
||||
/**
|
||||
* Ключ не содержит вложений, хотя от него требуется обратное.
|
||||
*/
|
||||
case KeyIsNotArray = 11;
|
||||
|
||||
/**
|
||||
* Класс не реализует интерфейс ISerializable.
|
||||
*/
|
||||
case NotISerializable = 12;
|
||||
|
||||
/**
|
||||
* Получает код ошибки из последней JSON ошибки.
|
||||
*
|
||||
* @return JsonErrorCode Код ошибки.
|
||||
*/
|
||||
public static function FromLastError (): JsonErrorCode
|
||||
{
|
||||
// Получаю код ошибки
|
||||
$error = json_last_error();
|
||||
|
||||
// Проверяю, что код ошибки в диапазоне [0; 10]
|
||||
if ($error < 0 || $error > 10)
|
||||
// - верну неизвестную ошибку, если код не в диапазоне
|
||||
return self::Unknown;
|
||||
|
||||
// Перевожу код в Enum
|
||||
return self::FromInt($error);
|
||||
}
|
||||
}
|
40
sources/enums/ObjectArraySerializeMethod.php
Normal file
40
sources/enums/ObjectArraySerializeMethod.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление типов сериализации массива объектов.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.1
|
||||
*/
|
||||
enum ObjectArraySerializeMethod: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Сериализация массива объектов с помощью serialize.
|
||||
*/
|
||||
case Serialize = 1;
|
||||
|
||||
/**
|
||||
* Сериализация массива объектов с помощью json_encode.
|
||||
*
|
||||
* @warning Для корректной работы требуется наличие json_encode в php.ini
|
||||
* @warning Этот способ сериализации НЕ РЕКОМЕНДУЕТСЯ для массивов объектов, представляющих собой классы, так как
|
||||
* при десериализации классы не будут созданы: вместо этого будет созданы объекты класса stdClass. Вместо этого
|
||||
* следует использовать метод JsonEncodeWithToArray.
|
||||
*/
|
||||
case JsonEncode = 2;
|
||||
|
||||
/**
|
||||
* Сериализация массива объектов с помощью ToArray, который возвращает массив. Этот массив впоследствии
|
||||
* сериализуется с помощью json_encode. Десерилизация происходит в обратном порядке.
|
||||
*/
|
||||
case JsonEncodeWithToArray = 3;
|
||||
}
|
34
sources/enums/VarNotBoolAction.php
Normal file
34
sources/enums/VarNotBoolAction.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление типов действий, которые необходимо выполнить, если переменная не является булевым типом.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.19
|
||||
*/
|
||||
enum VarNotBoolAction: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Игнорировать это утверждение.
|
||||
*/
|
||||
case Ignore = 0;
|
||||
|
||||
/**
|
||||
* Считать это утверждение истинным.
|
||||
*/
|
||||
case ConsiderItTrue = 1;
|
||||
|
||||
/**
|
||||
* Считать это утверждение ложным.
|
||||
*/
|
||||
case ConsiderItFalse = 2;
|
||||
}
|
29
sources/enums/VersionCompareRangeOption.php
Normal file
29
sources/enums/VersionCompareRangeOption.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление параметров для сравнения версий на промежутке.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.27
|
||||
*/
|
||||
enum VersionCompareRangeOption: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Левая граница включается в диапазон.
|
||||
*/
|
||||
case LeftBorderIncluded = 0;
|
||||
|
||||
/**
|
||||
* Правая граница включается в диапазон.
|
||||
*/
|
||||
case RightBorderIncluded = 1;
|
||||
}
|
49
sources/enums/VersionInfoStage.php
Normal file
49
sources/enums/VersionInfoStage.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\enums;
|
||||
|
||||
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Перечисление стадий в информации о версии.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.24
|
||||
*/
|
||||
enum VersionInfoStage: int
|
||||
{
|
||||
// Подключаю расширение для Enum
|
||||
use EnumExtensionsTrait;
|
||||
|
||||
/**
|
||||
* Не определена или не задана стадия.
|
||||
*/
|
||||
case Undefined = 0;
|
||||
|
||||
/**
|
||||
* Пре-алфа.
|
||||
*/
|
||||
case PreAlpha = 1;
|
||||
|
||||
/**
|
||||
* Альфа.
|
||||
*/
|
||||
case Alpha = 2;
|
||||
|
||||
/**
|
||||
* Бета.
|
||||
*/
|
||||
case Beta = 3;
|
||||
|
||||
/**
|
||||
* Кандидат в релиз.
|
||||
*/
|
||||
case ReleaseCandidate = 4;
|
||||
|
||||
/**
|
||||
* Релиз.
|
||||
*/
|
||||
case Stable = 5;
|
||||
}
|
67
sources/exceptions/JsonException.php
Normal file
67
sources/exceptions/JsonException.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\exceptions;
|
||||
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\enums\JsonErrorCode;
|
||||
|
||||
/**
|
||||
* Ошибка работы с JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
final class JsonException extends Exception
|
||||
{
|
||||
/**
|
||||
* @var string|null $JsonString Строка JSON.
|
||||
*/
|
||||
public ?string $JsonString;
|
||||
|
||||
/**
|
||||
* @var JsonErrorCode $ErrorCode Код ошибки JSON.
|
||||
*/
|
||||
public JsonErrorCode $ErrorCode;
|
||||
|
||||
/**
|
||||
* @link https://www.php.net/manual/ru/function.json-last-error-msg.php
|
||||
* @var string|null $ErrorMessage Сообщение об ошибке JSON.
|
||||
*
|
||||
* Внимание! В отличие от функции json_last_error_msg(), данная переменная при отсутствии ошибок выводит null, а не
|
||||
* "No error".
|
||||
*/
|
||||
public ?string $ErrorMessage;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param string|null $json Строка JSON.
|
||||
* @param JsonErrorCode $errorCode Код ошибки JSON.
|
||||
* @param string|null $errorMessage Сообщение об ошибке JSON.
|
||||
*/
|
||||
public function __construct (?string $json = null, JsonErrorCode $errorCode = JsonErrorCode::Unknown,
|
||||
?string $errorMessage = null)
|
||||
{
|
||||
// Если код ошибки JSON равен 0
|
||||
if ($errorMessage === "No error")
|
||||
// - то присваиваем ему null для совместимости
|
||||
$errorMessage = null;
|
||||
|
||||
// Сохраняем сообщение об ошибке
|
||||
$this->ErrorMessage = $errorMessage;
|
||||
|
||||
// Если сообщение пусто, то присваиваем ему "" для совместимости
|
||||
$errorMessage = $errorMessage ?? "";
|
||||
|
||||
// Запускаем базовый конструктор
|
||||
parent::__construct($errorMessage);
|
||||
|
||||
// Присваиваем имя файла
|
||||
$this->JsonString = $json;
|
||||
|
||||
// Присваиваем код ошибки
|
||||
$this->ErrorCode = $errorCode;
|
||||
}
|
||||
}
|
36
sources/exceptions/TypeException.php
Normal file
36
sources/exceptions/TypeException.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Ошибка работы с расширением типов.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.1
|
||||
*/
|
||||
final class TypeException extends Exception
|
||||
{
|
||||
/**
|
||||
* @var string $TypeName Имя типа.
|
||||
*/
|
||||
public string $TypeName;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param string $typeName Имя типа.
|
||||
* @param string $message Сообщение об ошибке.
|
||||
*/
|
||||
public function __construct (string $typeName = "", string $message = "")
|
||||
{
|
||||
// Запускаем базовый конструктор
|
||||
parent::__construct($message);
|
||||
|
||||
// Присваиваем тип
|
||||
$this->TypeName = $typeName;
|
||||
}
|
||||
}
|
90
sources/extensions/BoolExtensions.php
Normal file
90
sources/extensions/BoolExtensions.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\extensions;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\VarNotBoolAction;
|
||||
|
||||
/**
|
||||
* Расширение типа "правда/ложь".
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.1
|
||||
* @since 1.0.7
|
||||
*/
|
||||
final class BoolExtensions
|
||||
{
|
||||
/**
|
||||
* Вывод в строку <code>ifTrue</code>, если выражение <code>b</code> правдиво и <code>ifFalse</code> в противном
|
||||
* случае.
|
||||
*
|
||||
* @param bool $b Выражение типа правда/ложь.
|
||||
* @param string $ifTrue Строка для правдивого выражения. По умолчанию "true".
|
||||
* @param string $ifFalse Строка для лживого выражения. По умолчанию "false".
|
||||
*
|
||||
* @return string Вывод строки.
|
||||
*/
|
||||
public static function ExportToString (bool $b, string $ifTrue = "true", string $ifFalse = "false"): string
|
||||
{
|
||||
return $b ? $ifTrue : $ifFalse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вычисляет, есть ли хотя бы одно из переменных формата правда/ложь <code>expressions</code> в значении
|
||||
* <code>true</code>.
|
||||
*
|
||||
* @param array $expressions Переменные формата правда/ложь.
|
||||
* @param VarNotBoolAction $ifNotBool Действие, если какой-то аргумент <code>expressions</code> не является булевым
|
||||
* типом. По умолчанию игнорировать.
|
||||
*
|
||||
* @return bool Есть ли хотя бы одно в значении true.
|
||||
*
|
||||
*/
|
||||
public static function AnyTrue (array $expressions, VarNotBoolAction $ifNotBool = VarNotBoolAction::Ignore): bool
|
||||
{
|
||||
return self::TrueCount($expressions, $ifNotBool) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вычисляет количество переменных формата правда/ложь <code>expressions</code> в значении <code>true</code>.
|
||||
*
|
||||
* @param array $expressions Переменные формата правда/ложь.
|
||||
* @param VarNotBoolAction $ifNotBool Действие, если какой-то аргумент <code>expressions</code> не является булевым
|
||||
* типом. По умолчанию игнорировать.
|
||||
*
|
||||
* @return int Количество переменных в значении true.
|
||||
*/
|
||||
public static function TrueCount (array $expressions, VarNotBoolAction $ifNotBool = VarNotBoolAction::Ignore): int
|
||||
{
|
||||
// Создаем пустой массив для хранения проверяемых аргументов
|
||||
$checkArray = [];
|
||||
|
||||
// Проверяем все входящие аргументы
|
||||
foreach ($expressions as $expression)
|
||||
// - если аргумент не является типом правда/ложь
|
||||
if (!is_bool($expression))
|
||||
// -- то делаем следующее в зависимости от настроек:
|
||||
switch ($ifNotBool) {
|
||||
case VarNotBoolAction::Ignore:
|
||||
// --- игнорируем аргумент
|
||||
break;
|
||||
case VarNotBoolAction::ConsiderItTrue:
|
||||
// --- считаем аргумент как истинное значение
|
||||
$checkArray[] = true;
|
||||
break;
|
||||
case VarNotBoolAction::ConsiderItFalse:
|
||||
// --- считаем аргумент как ложное значение
|
||||
$checkArray[] = false;
|
||||
break;
|
||||
}
|
||||
else
|
||||
// - иначе добавляем аргумент в массив проверяемых аргументов
|
||||
$checkArray[] = $expression;
|
||||
|
||||
// Используем array_filter для фильтрации всех истинных значений
|
||||
$filtered = array_filter($checkArray, fn ($value) => $value === true);
|
||||
|
||||
// Возвращаем количество элементов в отфильтрованном массиве
|
||||
return count($filtered);
|
||||
}
|
||||
}
|
@@ -207,4 +207,63 @@ final class StringExtension
|
||||
// Возвращаю обрезанный текст
|
||||
return mb_substr($text, 0, $lengthWithoutEndDots) . $endDots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция заменяет все вхождения строк поиск на соответствующие строки замены в заданной строке.
|
||||
*
|
||||
* @param array $searchReplace Массив с парами поиска и замены. Например, <code>['-' => '#', '$' => '%']</code>
|
||||
* заменит все дефисы на # и все доллары на %.
|
||||
* @param string $subject Строка, в которой нужно выполнить замену.
|
||||
* @param string $encoding (необязательный) Кодировка (по умолчанию, UTF-8).
|
||||
*
|
||||
* @return string Возвращает новую строку с выполненными заменами.
|
||||
*/
|
||||
public static function ReplaceAll (array $searchReplace, string $subject, string $encoding = 'UTF-8'): string
|
||||
{
|
||||
// Создаю результат
|
||||
$result = $subject;
|
||||
|
||||
// Для каждой пары поиска и замены
|
||||
foreach ($searchReplace as $search => $replace)
|
||||
// - заменяю все вхождения строки поиска на строку замены в заданной строке
|
||||
$result = self::Replace($search, $replace, $result, $encoding);
|
||||
|
||||
// Возвращаю результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция заменяет все вхождения строки поиска на строку замены в заданной строке (аналог mb_str_replace).
|
||||
*
|
||||
* @param string $search Строка, которую нужно найти и заменить.
|
||||
* @param string $replace Строка, на которую нужно заменить найденную строку.
|
||||
* @param string $subject Строка, в которой нужно выполнить замену.
|
||||
* @param string $encoding (необязательный) Кодировка (по умолчанию, UTF-8).
|
||||
*
|
||||
* @return string Возвращает новую строку с выполненной заменой.
|
||||
*/
|
||||
public static function Replace (string $search, string $replace, string $subject,
|
||||
string $encoding = 'UTF-8'): string
|
||||
{
|
||||
// Если кодировка не UTF-8
|
||||
if ($encoding != 'UTF-8') {
|
||||
// - то перекодируем строку поиска, замены и исходную строку в UTF-8
|
||||
$search = mb_convert_encoding($search, 'UTF-8', $encoding);
|
||||
// - и перекодируем строку замены в UTF-8
|
||||
$replace = mb_convert_encoding($replace, 'UTF-8', $encoding);
|
||||
// - и перекодируем исходную строку в UTF-8
|
||||
$subject = mb_convert_encoding($subject, 'UTF-8', $encoding);
|
||||
}
|
||||
|
||||
// С помощью регулярного выражения заменяем все вхождения строки поиска на строку замены
|
||||
$result = preg_replace('/' . preg_quote($search, '/') . '/u', $replace, $subject);
|
||||
|
||||
// Если кодировка не UTF-8
|
||||
if ($encoding != 'UTF-8')
|
||||
// - то перекодируем результат в исходную кодировку
|
||||
$result = mb_convert_encoding($result, $encoding, 'UTF-8');
|
||||
|
||||
// Возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
}
|
179
sources/extensions/TypeExtension.md
Normal file
179
sources/extensions/TypeExtension.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# Описание класса TypeExtension
|
||||
|
||||
## Информация о версии
|
||||
|
||||
Версия класса: 1.0
|
||||
|
||||
Впервые введено в пакет с версии: 1.1.1
|
||||
|
||||
Описание класса: Расширение для любого типа.
|
||||
|
||||
## Публичные свойства и константы класса
|
||||
|
||||
К публичным свойствам можно отнести следующие статичные функции: `DEFAULT_TO_ARRAY_ON_CLASS` и
|
||||
`DEFAULT_FROM_ARRAY_ON_CLASS`. Они описывают методы обработки классов по умолчанию для методов `ToArray` и `FromArray`
|
||||
соответственно.
|
||||
|
||||
### Метод `DEFAULT_TO_ARRAY_ON_CLASS`
|
||||
|
||||
Этот метод возвращает `Closure`, который можно использовать (и он используется при значении параметра `null`) во втором
|
||||
параметре метода `ToArray`.
|
||||
|
||||
### Метод `DEFAULT_FROM_ARRAY_ON_CLASS`
|
||||
|
||||
Этот метод возвращает `Closure`, который можно использовать (и он используется при значении параметра `null`) во втором
|
||||
параметре метода `FromArray`.
|
||||
|
||||
## Методы и функции
|
||||
|
||||
### Метод `ToArray`
|
||||
|
||||
Этот _статический_ метод переводит класс в массив. Он содержит **1 обязательный параметр**:
|
||||
|
||||
* `object $class` - класс, который нужно перевести в массив
|
||||
|
||||
и **1 необязательный параметр**:
|
||||
|
||||
* `?callable $onClass = null` - метод обработки классов. Если передаётся `null`, то используется
|
||||
`DEFAULT_TO_ARRAY_ON_CLASS`. По умолчанию, `null`.
|
||||
|
||||
В качестве метода обработки классов `onClass` подойдет любое `Closure` вида
|
||||
|
||||
fn (object $class): array => <ДЕЙСТВИЕ>;
|
||||
|
||||
Метод возвращает `array` - массив публичных свойств.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function ToArray (object $class, ?callable $onClass = null): array
|
||||
|
||||
Пример,
|
||||
|
||||
// Создаём тестовый класс (см. TypeExtensionTest)
|
||||
$class = new D (
|
||||
'test_string',
|
||||
12345,
|
||||
true,
|
||||
new A("test_string_A", 6789, false),
|
||||
new B("test_string_B", 9876, "false"),
|
||||
new C("test_string_C", 54321, true)
|
||||
);
|
||||
|
||||
// Создаём метод обработки классов
|
||||
// - воспользуемся тем, что класс C реализует интерфейс ISerialize
|
||||
$c_closure = fn (C $class): array =>
|
||||
[
|
||||
"type_class" => C::class,
|
||||
"type_value" => $class->Serialize()
|
||||
];
|
||||
|
||||
// - зададим метод обработки
|
||||
$closure = fn (object $class): array => $class instanceof C
|
||||
? $c_closure($class)
|
||||
: TypeExtension::ToArray($class);
|
||||
|
||||
// Преобразуем в массив
|
||||
try {
|
||||
$array = TypeExtension::ToArray($class, $closure);
|
||||
}
|
||||
catch (TypeException $e) {
|
||||
// - если ошибка, то выводим её и завершаем работу
|
||||
die($e->getMessage());
|
||||
}
|
||||
|
||||
// Вывожу в файл
|
||||
file_put_contents(__DIR__ . "/class.txt", json_encode($array, JSON_PRETTY_PRINT));
|
||||
|
||||
В результате содержимое файла:
|
||||
|
||||
{
|
||||
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\D",
|
||||
"stringD": "test_string",
|
||||
"intD": 12345,
|
||||
"boolD": true,
|
||||
"a": {
|
||||
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\A",
|
||||
"a": "test_string_A",
|
||||
"b": 6789,
|
||||
"c": false
|
||||
},
|
||||
"b": {
|
||||
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\B",
|
||||
"a": "test_string_B",
|
||||
"b": 9876,
|
||||
"d": "false"
|
||||
},
|
||||
"c": {
|
||||
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\C",
|
||||
"type_value": "{\"string\":\"test_string_C\",\"int\":54321,\"bool\":true}"
|
||||
}
|
||||
}
|
||||
|
||||
#### Выбрасываемые исключения
|
||||
|
||||
Этот метод выбрасывает исключение типа `TypeException` в случае, если объект `$class` (обязательный параметр метода) не является классом.
|
||||
|
||||
### Метод `FromArray`
|
||||
|
||||
Этот _статический_ метод переводит массив в класс. Он содержит **1 обязательный параметр**:
|
||||
|
||||
* `array $array` - массив публичных свойств
|
||||
|
||||
и **1 необязательный параметр**:
|
||||
|
||||
* `?callable $onClass = null` - метод обработки классов. Если передаётся `null`, то используется
|
||||
`DEFAULT_FROM_ARRAY_ON_CLASS`. По умолчанию, `null`.
|
||||
|
||||
В качестве метода обработки классов `onClass` подойдет любое `Closure` вида
|
||||
|
||||
fn (array $classArray): object => <ДЕЙСТВИЕ>;
|
||||
|
||||
Метод возвращает `object` - экземпляр класса.
|
||||
|
||||
Синтаксис:
|
||||
|
||||
public static function FromArray (array $array, ?callable $onClass = null): object
|
||||
|
||||
Пример,
|
||||
|
||||
// Считываем данные из файла и преобразуем в массив
|
||||
$array = json_decode(file_get_contents(__DIR__ . "/class.txt"), true);
|
||||
|
||||
// Создаём метод обработки классов
|
||||
// - воспользуемся тем, что класс C реализует интерфейс ISerialize
|
||||
$c_closure = function (string $serializedC): C
|
||||
{
|
||||
$classC = new C();
|
||||
$classC->UnSerialize($serializedC);
|
||||
return $classC;
|
||||
};
|
||||
|
||||
// - зададим метод обработки
|
||||
$closure = fn (array $classArray): object =>
|
||||
$classArray['type_class'] == C::class
|
||||
? $c_closure($classArray["type_value"])
|
||||
: TypeExtension::FromArray($classArray);
|
||||
|
||||
// Преобразуем в объект
|
||||
try {
|
||||
$class = TypeExtension::FromArray($array, D::CLOSURE_FROM_ARRAY());
|
||||
} catch (TypeException $e) {
|
||||
// - если ошибка, то выводим её и завершаем работу
|
||||
die($e->getMessage());
|
||||
}
|
||||
|
||||
// Вывожу тестовую строку
|
||||
echo $class->c->stringC;
|
||||
|
||||
В результате на экране отобразится:
|
||||
|
||||
test_string_C
|
||||
|
||||
#### Выбрасываемые исключения
|
||||
|
||||
Этот метод выбрасывает исключение типа `TypeException` в случаях, если:
|
||||
|
||||
* массив `$array` не создан через метод `ToArray`;
|
||||
* при попытке создать объект, он не создаётся;
|
||||
* дата передана не корректного формата;
|
||||
* пытается передать `null` не `nullable` типу.
|
235
sources/extensions/TypeExtension.php
Normal file
235
sources/extensions/TypeExtension.php
Normal file
@@ -0,0 +1,235 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\extensions;
|
||||
|
||||
use Closure;
|
||||
use DateMalformedStringException;
|
||||
use DateTime;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Расширение для любого типа.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.1
|
||||
*/
|
||||
final class TypeExtension
|
||||
{
|
||||
/**
|
||||
* Дефолтный метод обработки классов для ToArray.
|
||||
*
|
||||
* @return Closure Метод обработки классов для ToArray.
|
||||
*/
|
||||
public static function DEFAULT_TO_ARRAY_ON_CLASS (): Closure
|
||||
{
|
||||
return fn (object $class): array => self::ToArray($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Переводит объект в массив.
|
||||
*
|
||||
* @param object $class Объект.
|
||||
* @param callable|null $onClass Метод обработки классов. Если передаётся null, то используется
|
||||
* <code>DEFAULT_TO_ARRAY_ON_CLASS</code>. По умолчанию, null.
|
||||
*
|
||||
* @return array Массив свойств типа.
|
||||
* @throws TypeException Исключение, если объект не является классом.
|
||||
*/
|
||||
public static function ToArray (object $class, ?callable $onClass = null): array
|
||||
{
|
||||
// Проверяю, что метод обработки классов не null и если null, то присваиваю дефолтный метод
|
||||
$onClass ??= self::DEFAULT_TO_ARRAY_ON_CLASS();
|
||||
|
||||
// Создаю массив результата
|
||||
$result = [];
|
||||
|
||||
// Сперва проверяю, что объект является классом
|
||||
if (!is_object($class))
|
||||
// - если нет, то выбрасываю исключение
|
||||
throw new TypeException($class::class, "Object is not class / Объект не является классом.");
|
||||
|
||||
// Затем записываю имя класса
|
||||
$result["type_class"] = $class::class;
|
||||
|
||||
// Получаю свойства класса
|
||||
$properties = get_object_vars($class);
|
||||
|
||||
// Для каждого свойства класса
|
||||
foreach ($properties as $key => $value) {
|
||||
// - если значение является датой
|
||||
if ($value instanceof DateTimeInterface) {
|
||||
|
||||
// -- добавляю в массив
|
||||
$result[$key] = $value->getTimestamp();
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является перечислением
|
||||
if ($value instanceof UnitEnum) {
|
||||
// -- получаю перечисление
|
||||
$result[$key] = $value->name;
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является NULL
|
||||
if (is_null($value)) {
|
||||
// -- присваиваю NULL
|
||||
$result[$key] = "null";
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является классом
|
||||
if (is_object($value)) {
|
||||
// -- добавляю в массив через рекурсию
|
||||
$result[$key] = $onClass($value);
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - присваиваю значение
|
||||
$result[$key] = $value;
|
||||
}
|
||||
|
||||
// Возвращаю результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Дефолтный метод обработки классов для FromArray.
|
||||
*
|
||||
* @return Closure Метод обработки классов для FromArray.
|
||||
*/
|
||||
public static function DEFAULT_FROM_ARRAY_ON_CLASS (): Closure
|
||||
{
|
||||
return fn (array $classArray): object => self::FromArray($classArray);
|
||||
}
|
||||
|
||||
/**
|
||||
* Переводит массив в объект.
|
||||
*
|
||||
* @param array $array Массив свойств.
|
||||
* @param callable|null $onClass Метод обработки классов. Если передаётся null, то используется
|
||||
* <code>DEFAULT_FROM_ARRAY_ON_CLASS</code>. По умолчанию, null.
|
||||
*
|
||||
* @return mixed Восстановленный объект.
|
||||
* @throws TypeException Исключение, если массив не создан через ToArray, объект не создан, дата не корректного
|
||||
* формата или пытается передать null не nullable типу.
|
||||
*/
|
||||
public static function FromArray (array $array, ?callable $onClass = null): object
|
||||
{
|
||||
// Проверяю, что массив является массивом, созданным через ToArray, то есть содержит ключ type_class
|
||||
if (!array_key_exists("type_class", $array))
|
||||
// - если нет, то выбрасываю исключение
|
||||
throw new TypeException("array", "Array is not created by ToArray / Массив не создан через ToArray.");
|
||||
|
||||
// Получаю имя класса
|
||||
$className = $array["type_class"];
|
||||
|
||||
// Создаем объект
|
||||
$instance = new $className();
|
||||
|
||||
// Проверяем, что объект создан
|
||||
if (!is_object($instance) && $instance instanceof $className)
|
||||
// - если нет, то выбрасываю исключение
|
||||
throw new TypeException($className, "Object is not created / Объект не создан.");
|
||||
|
||||
// Получаю свойства класса
|
||||
$properties = get_object_vars($instance);
|
||||
|
||||
// Для каждого свойства класса
|
||||
foreach ($properties as $key => $value) {
|
||||
// - проверяю, есть ли свойство в массиве
|
||||
if (!array_key_exists($key, $array))
|
||||
// -- если нет, то пропускаю
|
||||
continue;
|
||||
|
||||
// - получаю значение из массива
|
||||
$value = $array[$key];
|
||||
|
||||
// - если значение является датой DateTime
|
||||
if ($instance->$key instanceof DateTime && is_int($value)) {
|
||||
// -- присваиваю значение
|
||||
try {
|
||||
$instance->$key = new DateTime ('@' . $value);
|
||||
}
|
||||
catch (DateMalformedStringException) {
|
||||
throw new TypeException($className . "->{$key}::DateTime",
|
||||
"Date is not correct format / Дата не корректного формата.");
|
||||
}
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является датой DateTimeImmutable
|
||||
if ($instance->$key instanceof DateTimeImmutable && is_int($value)) {
|
||||
// -- присваиваю значение
|
||||
try {
|
||||
$instance->$key = new DateTimeImmutable('@' . $value);
|
||||
}
|
||||
catch (DateMalformedStringException) {
|
||||
throw new TypeException($className . "->{$key}::DateTimeImmutable",
|
||||
"Date is not correct format / Дата не корректного формата.");
|
||||
}
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является перечислением
|
||||
if ($instance->$key instanceof UnitEnum) {
|
||||
// -- получаю все значения перечисления
|
||||
foreach ($instance->$key::getCases() as $case)
|
||||
// --- если значение совпадает
|
||||
if ($case->name === $value)
|
||||
// ---- присваиваю значение
|
||||
$instance->$key = $case;
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является NULL
|
||||
if (is_string($value) && $value == "null") {
|
||||
// -- присваиваю NULL
|
||||
try {
|
||||
$instance->$key = null;
|
||||
}
|
||||
catch (Exception $exception) {
|
||||
throw new TypeException($className . "->$key",
|
||||
"Cannot assign null to non-nullable property. / Невозможно присвоить null не nullable типу: {$exception->getMessage()}.");
|
||||
}
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является классом
|
||||
if (is_object($instance->$key) && is_array($array[$key]) && array_key_exists("type_class", $array[$key])) {
|
||||
// -- добавляю в массив через рекурсию
|
||||
$instance->$key = $onClass($array[$key]);
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - присваиваю значение
|
||||
$instance->$key = $value;
|
||||
}
|
||||
|
||||
// Возвращаю объект
|
||||
return $instance;
|
||||
}
|
||||
}
|
30
sources/interfaces/IArrayable.php
Normal file
30
sources/interfaces/IArrayable.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\interfaces;
|
||||
|
||||
/**
|
||||
* Интерфейс, указывающий, что класс может быть переведён в массив и обратно.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.2
|
||||
*/
|
||||
interface IArrayable
|
||||
{
|
||||
/**
|
||||
* Переводит объект в массив.
|
||||
*
|
||||
* @return array Массив объекта.
|
||||
*/
|
||||
public function ToArray (): array;
|
||||
|
||||
/**
|
||||
* Переводит массив в объект.
|
||||
*
|
||||
* @param array $array Массив.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function FromArray (array $array): void;
|
||||
}
|
21
sources/interfaces/IDuplicated.php
Normal file
21
sources/interfaces/IDuplicated.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\interfaces;
|
||||
|
||||
/**
|
||||
* Интерфейс реализации дублирования классов.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package freecms
|
||||
* @version 0.1
|
||||
* @since 0.1
|
||||
*/
|
||||
interface IDuplicated
|
||||
{
|
||||
/**
|
||||
* Дублирование класса.
|
||||
*
|
||||
* @return object Класс-дублёр.
|
||||
*/
|
||||
public function Duplicate (): object;
|
||||
}
|
32
sources/interfaces/IStoredAtSQL.php
Normal file
32
sources/interfaces/IStoredAtSQL.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\interfaces;
|
||||
|
||||
/**
|
||||
* Интерфейс поддержки моделей и классов, реализующих хранение свойств в SQL базе данных.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package freecms
|
||||
* @version 0.1
|
||||
* @since 0.1
|
||||
*/
|
||||
interface IStoredAtSQL
|
||||
{
|
||||
/**
|
||||
* Вывод параметров добавления/обновления данных в базу данных.
|
||||
*
|
||||
* @param bool $withId Нужно ли добавлять Id в массив
|
||||
*
|
||||
* @return array Массив параметров
|
||||
*/
|
||||
public function ToSQL (bool $withId = true): array;
|
||||
|
||||
/**
|
||||
* Преобразование данных из базы данных в модель, класс.
|
||||
*
|
||||
* @param array $sqlData Данные из базы данных
|
||||
*
|
||||
* @return self Класс модели с заполненными данными из базы данных
|
||||
*/
|
||||
public function FromSQL (array $sqlData): self;
|
||||
}
|
78
sources/models/ActionStateMessage.php
Normal file
78
sources/models/ActionStateMessage.php
Normal file
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\models;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
/**
|
||||
* Модель сообщения о состоянии.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.1
|
||||
* @since 1.0
|
||||
*/
|
||||
final class ActionStateMessage implements ISerializable
|
||||
{
|
||||
/**
|
||||
* @var MessageType $MessageType Тип сообщения
|
||||
*/
|
||||
public MessageType $MessageType;
|
||||
|
||||
/**
|
||||
* @var bool $IsCritical Критичность сообщения
|
||||
*/
|
||||
public bool $IsCritical;
|
||||
|
||||
/**
|
||||
* @var string $Message Текст сообщения
|
||||
*/
|
||||
public string $Message;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param MessageType $type Тип сообщения
|
||||
* @param bool $isCritical Критичность сообщения
|
||||
* @param string $message Текст сообщения
|
||||
*/
|
||||
public function __construct (MessageType $type = MessageType::Info, bool $isCritical = false, string $message = "")
|
||||
{
|
||||
$this->MessageType = $type;
|
||||
$this->IsCritical = $isCritical;
|
||||
$this->Message = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
// Десериализую массив
|
||||
$array = json_decode($serialized, true);
|
||||
|
||||
// Заполняю поля
|
||||
$this->MessageType =
|
||||
isset($array["MessageType"]) ? MessageType::FromName($array["MessageType"]) : MessageType::Info;
|
||||
$this->IsCritical = isset($array["IsCritical"]) && $array["IsCritical"] == 1;
|
||||
$this->Message = $array["Message"] ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
// Создаю массив результата
|
||||
$result = [];
|
||||
|
||||
// Заполняю массив
|
||||
$result["MessageType"] = $this->MessageType->GetValue();
|
||||
$result["IsCritical"] = $this->IsCritical ? 1 : 0;
|
||||
$result["Message"] = $this->Message;
|
||||
|
||||
// Сериализую
|
||||
return json_encode($result);
|
||||
}
|
||||
}
|
@@ -1,108 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\models;
|
||||
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\classes\ClassMapper;
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Класс сообщения состояния.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0
|
||||
*/
|
||||
final class ActionStateMessageModel implements ISerializable
|
||||
{
|
||||
/**
|
||||
* @var MessageType $MessageType Тип сообщения
|
||||
*/
|
||||
public MessageType $MessageType;
|
||||
|
||||
/**
|
||||
* @var bool $IsCritical Критичность сообщения
|
||||
*/
|
||||
public bool $IsCritical;
|
||||
|
||||
/**
|
||||
* @var string $Message Текст сообщения
|
||||
*/
|
||||
public string $Message;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param MessageType $type Тип сообщения
|
||||
* @param bool $isCritical Критичность сообщения
|
||||
* @param string $message Текст сообщения
|
||||
*/
|
||||
public function __construct (MessageType $type = MessageType::Info, bool $isCritical = false, string $message = "")
|
||||
{
|
||||
$this->MessageType = $type;
|
||||
$this->IsCritical = $isCritical;
|
||||
$this->Message = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
// Десериализую массив
|
||||
$thisNew = unserialize($serialized);
|
||||
|
||||
try {
|
||||
// Получаю класс
|
||||
$class = ClassMapper::MapToClassProperty(get_class($this), $thisNew);
|
||||
}
|
||||
catch (Exception) {
|
||||
$class = new ActionStateMessageModel();
|
||||
}
|
||||
|
||||
// Заполняю текущий класс
|
||||
ClassMapper::MapClass($class, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
// Создаю массив результата
|
||||
$result = [];
|
||||
|
||||
// Получаю свойства класса
|
||||
$properties = get_object_vars($this);
|
||||
|
||||
// Для каждого свойства класса
|
||||
foreach ($properties as $key => $value) {
|
||||
|
||||
// - если значение является перечислением
|
||||
if ($value instanceof UnitEnum) {
|
||||
// -- получаю перечисление
|
||||
$result[$key] = $value->name;
|
||||
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - если значение является NULL
|
||||
if ($value == null) {
|
||||
// -- присваиваю NULL
|
||||
$result[$key] = "null";
|
||||
// -- следующий элемент
|
||||
continue;
|
||||
}
|
||||
|
||||
// - присваиваю значение
|
||||
$result[$key] = $value;
|
||||
}
|
||||
|
||||
// Сериализую массив и вывожу его
|
||||
return serialize($result);
|
||||
}
|
||||
}
|
52
sources/models/ObjectArraySerializeOptions.php
Normal file
52
sources/models/ObjectArraySerializeOptions.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\models;
|
||||
|
||||
use Closure;
|
||||
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||
|
||||
/**
|
||||
* Модель настроек сериализации для класса ObjectArray.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.1
|
||||
*/
|
||||
final class ObjectArraySerializeOptions
|
||||
{
|
||||
/**
|
||||
* @var ObjectArraySerializeMethod $SerializeMethod Метод сериализации/десериализации.
|
||||
*/
|
||||
public ObjectArraySerializeMethod $SerializeMethod;
|
||||
|
||||
/**
|
||||
* @var Closure|null $OnClassTo Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray.
|
||||
* Она передается в качестве параметра в функцию ToArray и служит для правильного преобразования типа в массив.
|
||||
*/
|
||||
public ?Closure $OnClassTo;
|
||||
|
||||
/**
|
||||
* @var Closure|null $OnClassFrom Функция обратного вызова для десериализации объекта методом
|
||||
* JsonEncodeWithToArray. Она передается в качестве параметра в функцию FromArray и служит для правильного
|
||||
* преобразования массива в тип.
|
||||
*/
|
||||
public ?Closure $OnClassFrom;
|
||||
|
||||
/**
|
||||
* Конструктор.
|
||||
*
|
||||
* @param ObjectArraySerializeMethod $serializeMethod Метод сериализации/десериализации.
|
||||
* @param callable|null $onClassTo Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray
|
||||
* (для ToArray).
|
||||
* @param callable|null $onClassFrom Функция обратного вызова для десериализации объекта методом
|
||||
* JsonEncodeWithToArray (для FromArray).
|
||||
*/
|
||||
public function __construct (ObjectArraySerializeMethod $serializeMethod = ObjectArraySerializeMethod::Serialize,
|
||||
?callable $onClassTo = null, ?callable $onClassFrom = null)
|
||||
{
|
||||
$this->SerializeMethod = $serializeMethod;
|
||||
$this->OnClassTo = $onClassTo;
|
||||
$this->OnClassFrom = $onClassFrom;
|
||||
}
|
||||
}
|
114
sources/traits/ActionState/ActionStateAddTrait.php
Normal file
114
sources/traits/ActionState/ActionStateAddTrait.php
Normal file
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ActionState;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ActionState;
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||
|
||||
/**
|
||||
* Часть кода класса ActionState, отвечающая за методы добавления сообщений.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.13
|
||||
*/
|
||||
trait ActionStateAddTrait
|
||||
{
|
||||
/**
|
||||
* Добавляет данные из другого состояния.
|
||||
*
|
||||
* @param ActionState $state Другое состояние
|
||||
* @param bool $clearAllBefore Очищать сообщения перед добавлением (true) или просто добавить к текущим (false)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddState (ActionState $state, bool $clearAllBefore = false): void
|
||||
{
|
||||
// Если нужно очистить список сообщений
|
||||
if ($clearAllBefore)
|
||||
// - то очищаю список сообщений
|
||||
$this->Clear(fn (ActionStateMessage $message) => true);
|
||||
|
||||
// Добавляю сообщения из другого состояния
|
||||
$this->AddRange($state->GetMessages(ActionState::GET_STRING_ALL()));
|
||||
|
||||
// Добавляю значение
|
||||
$this->Value = $state->Value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет список
|
||||
*
|
||||
* @param ObjectArray|array $messages Список сообщений
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddRange (ObjectArray|array $messages): void
|
||||
{
|
||||
// Добавляю сообщения
|
||||
$this->Messages->AddRange($messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет сообщение о критической ошибке.
|
||||
*
|
||||
* @param string $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddCritical (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessage(MessageType::Error, true, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавление сообщения.
|
||||
*
|
||||
* @param ActionStateMessage $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Add (ActionStateMessage $message): void
|
||||
{
|
||||
$this->Messages->Add($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет сообщение об ошибке.
|
||||
*
|
||||
* @param string $message Сообщение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddError (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessage(MessageType::Error, false, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет предупреждение.
|
||||
*
|
||||
* @param string $message Сообщение.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddWarning (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessage(MessageType::Warning, false, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет информационное сообщение.
|
||||
*
|
||||
* @param string $message Сообщение.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddInfo (string $message): void
|
||||
{
|
||||
$this->Add(new ActionStateMessage(MessageType::Info, false, $message));
|
||||
}
|
||||
}
|
45
sources/traits/ActionState/ActionStateGetTrait.php
Normal file
45
sources/traits/ActionState/ActionStateGetTrait.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ActionState;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
|
||||
/**
|
||||
* Часть кода класса ActionState, отвечающая за методы получения сообщений.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.13
|
||||
*/
|
||||
trait ActionStateGetTrait
|
||||
{
|
||||
/**
|
||||
* Возвращает список сообщений (параметр Message у каждого сообщения).
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
* @param string $separator Разделитель
|
||||
*
|
||||
* @return string Список сообщений
|
||||
*/
|
||||
public function GetStringMessages (callable $predicate, string $separator = '\n'): string
|
||||
{
|
||||
// Делаю выборку
|
||||
$result = $this->Messages->GetColumn("Message", $predicate);
|
||||
|
||||
// Возвращаю список
|
||||
return implode($separator, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбирает сообщения по условию predicate.
|
||||
*
|
||||
* @param callable $predicate Условие выборки
|
||||
*
|
||||
* @return ObjectArray Список отобранных сообщений
|
||||
*/
|
||||
public function GetMessages (callable $predicate): ObjectArray
|
||||
{
|
||||
return $this->Messages->GetRows($predicate);
|
||||
}
|
||||
}
|
68
sources/traits/ActionState/ActionStateHasTrait.php
Normal file
68
sources/traits/ActionState/ActionStateHasTrait.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ActionState;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||
|
||||
/**
|
||||
* Часть кода класса ActionState, отвечающая за методы проверки на наличие сообщений.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.13
|
||||
*/
|
||||
trait ActionStateHasTrait
|
||||
{
|
||||
/**
|
||||
* Проверяет, есть ли информационные сообщения.
|
||||
*
|
||||
* @return bool Наличие сообщений
|
||||
*/
|
||||
public function HasInfos (): bool
|
||||
{
|
||||
return $this->Messages->IsExist(fn (ActionStateMessage $message)
|
||||
=> $message->MessageType
|
||||
== MessageType::Info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, успешно ли завершилась операция.
|
||||
*
|
||||
* @param bool $onlyCritical Игнорировать все некритические ошибки и предупреждения (не рекомендуется!)
|
||||
*
|
||||
* @return bool Успешно ли завершилась операция.
|
||||
*/
|
||||
public function IsSuccess (bool $onlyCritical = false): bool
|
||||
{
|
||||
return ($onlyCritical) ? !$this->HasErrors($onlyCritical) : !$this->HasErrors() && !$this->HasWarnings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли ошибки.
|
||||
*
|
||||
* @param bool $onlyCritical Учитывать только критические ошибки.
|
||||
*
|
||||
* @return bool Наличие ошибок.
|
||||
*/
|
||||
public function HasErrors (bool $onlyCritical = false): bool
|
||||
{
|
||||
return $this->Messages->IsExist(fn (ActionStateMessage $message): bool
|
||||
=> $onlyCritical
|
||||
? $message->MessageType == MessageType::Error && $message->IsCritical
|
||||
: $message->MessageType == MessageType::Error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, есть ли предупреждения.
|
||||
*
|
||||
* @return bool Наличие предупреждений
|
||||
*/
|
||||
public function HasWarnings (): bool
|
||||
{
|
||||
return $this->Messages->IsExist(fn (ActionStateMessage $message)
|
||||
=> $message->MessageType
|
||||
== MessageType::Warning);
|
||||
}
|
||||
}
|
51
sources/traits/ActionState/ActionStateStaticTrait.php
Normal file
51
sources/traits/ActionState/ActionStateStaticTrait.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ActionState;
|
||||
|
||||
use Closure;
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||
|
||||
/**
|
||||
* Часть кода класса ActionState, отвечающая за статичные методы и константы.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0.13
|
||||
*/
|
||||
trait ActionStateStaticTrait
|
||||
{
|
||||
/**
|
||||
* При выводе GetStringMessages выводит только ошибки.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ERROR_ONLY (): Closure
|
||||
{
|
||||
return fn (ActionStateMessage $message)
|
||||
=> $message->MessageType === MessageType::Error;
|
||||
}
|
||||
|
||||
/**
|
||||
* При выводе GetStringMessages выводит ошибки и предупреждения.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ERROR_AND_WARNING (): Closure
|
||||
{
|
||||
return fn (ActionStateMessage $message)
|
||||
=> $message->MessageType === MessageType::Error
|
||||
|| $message->MessageType === MessageType::Warning;
|
||||
}
|
||||
|
||||
/**
|
||||
* При выводе GetStringMessages выводит все сообщения.
|
||||
*
|
||||
* @return Closure Возвращает функцию, проверяющую сообщение на соответствие типу.
|
||||
*/
|
||||
public static function GET_STRING_ALL (): Closure
|
||||
{
|
||||
return fn (ActionStateMessage $message) => true;
|
||||
}
|
||||
}
|
@@ -1,18 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ObjectArray;
|
||||
namespace goodboyalex\php_components_pack\traits;
|
||||
|
||||
use ArrayIterator;
|
||||
|
||||
/**
|
||||
* Часть кода класса ObjectArray, отвечающая за функции из наследуемых интерфейсов и классов.
|
||||
* Часть кода класса ObjectArray и Dictionary, отвечающая за функции из наследуемых интерфейсов и классов.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0
|
||||
*/
|
||||
trait ObjectArrayBasicTrait
|
||||
trait ArrayBasicTrait
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
@@ -69,7 +69,7 @@ trait ObjectArrayBasicTrait
|
||||
*/
|
||||
public function __isset (mixed $offset): bool
|
||||
{
|
||||
return isset($this->data[$offset]);
|
||||
return isset($this->Container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,6 +77,10 @@ trait ObjectArrayBasicTrait
|
||||
*/
|
||||
public function Serialize (): string
|
||||
{
|
||||
/**
|
||||
* ВНИМАНИЕ! Не используйте json_encode для сериализации объектов данного класса, так как он НЕ СОХРАНЯЕТ классы объектов!
|
||||
* Корректное восстановление объектов невозможно (восстанавливает только как ассоциативный массив).
|
||||
*/
|
||||
return serialize($this->Container);
|
||||
}
|
||||
|
||||
@@ -85,6 +89,10 @@ trait ObjectArrayBasicTrait
|
||||
*/
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
/**
|
||||
* ВНИМАНИЕ! Не используйте json_decode для десериализации объектов данного класса, так как он НЕ ВОССТАНОВЛЯЕТ
|
||||
* классы объектов! Корректное восстановление объектов невозможно (восстанавливается только как ассоциативный массив).
|
||||
*/
|
||||
$this->Container = unserialize($serialized);
|
||||
}
|
||||
}
|
69
sources/traits/JsonReWriter/JsonReWriterDeleteTrait.php
Normal file
69
sources/traits/JsonReWriter/JsonReWriterDeleteTrait.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\JsonReWriter;
|
||||
|
||||
/**
|
||||
* Часть кода класса JsonReWriter, отвечающая за методы удаления ключей JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
trait JsonReWriterDeleteTrait
|
||||
{
|
||||
/**
|
||||
* Очистка данных JSON.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (): void
|
||||
{
|
||||
// Очистка данных
|
||||
unset($this->JsonData);
|
||||
|
||||
// Создание пустого массива
|
||||
$this->JsonData = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаление ключа JSON.
|
||||
*
|
||||
* @param string $key Требуемый ключ JSON для удаления.
|
||||
*
|
||||
* @return bool Результат удаления ключа: <code>true</code> - удаление прошло успешно, <code>false</code> -
|
||||
* произошла ошибка при удалении.
|
||||
*/
|
||||
public function DeleteKey (string $key): bool
|
||||
{
|
||||
// Очищаем ключ
|
||||
$preparedKey = $this->PrepareKey($key);
|
||||
|
||||
// Проверка ключа
|
||||
if (!$this->IsKeyExists($preparedKey))
|
||||
// - ключ не существует
|
||||
return false;
|
||||
|
||||
// Разбиваем ключ на части
|
||||
$keys = $this->ParseKey($preparedKey);
|
||||
|
||||
// Получаем текущий массив данных
|
||||
$current = &$this->JsonData;
|
||||
|
||||
// Если ключ не является корневым
|
||||
if (count($keys) > 0)
|
||||
// - переходим к вложенному массиву
|
||||
for ($i = 0; $i < count($keys) - 1; $i++)
|
||||
// -- и добавляем массив данных
|
||||
$current = &$current[$keys[$i]];
|
||||
|
||||
// Получаем удаляемый ключ
|
||||
$deleteKey = $keys[count($keys) - 1];
|
||||
|
||||
// Удаляем ключ
|
||||
unset($current[$deleteKey]);
|
||||
|
||||
// Проверяем удаление
|
||||
return $this->IsKeyExists($key);
|
||||
}
|
||||
}
|
129
sources/traits/JsonReWriter/JsonReWriterKeyTrait.php
Normal file
129
sources/traits/JsonReWriter/JsonReWriterKeyTrait.php
Normal file
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\JsonReWriter;
|
||||
|
||||
use goodboyalex\php_components_pack\extensions\StringExtension;
|
||||
|
||||
/**
|
||||
* Часть кода класса JsonReWriter, отвечающая за методы работы с ключами JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
trait JsonReWriterKeyTrait
|
||||
{
|
||||
/**
|
||||
* Проверяем наличие ключа в JSON.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
*
|
||||
* @return bool true если ключ найден, false если нет.
|
||||
*/
|
||||
public function IsKeyExists (string $key): bool
|
||||
{
|
||||
// Получаем массив ключей по вложенности
|
||||
$keys = $this->ParseKey($key);
|
||||
|
||||
// Получаем текущий массив данных
|
||||
$current = $this->JsonData;
|
||||
|
||||
// Для каждого ключа
|
||||
foreach ($keys as $key) {
|
||||
// - проверяем наличие ключа в текущем массиве
|
||||
if (!array_key_exists($key, $current))
|
||||
// - нет? Возвращаем false
|
||||
return false;
|
||||
|
||||
// Переходим ко вложенному массиву
|
||||
$current = $current[$key];
|
||||
}
|
||||
|
||||
// Возвращаем true, если все ключи найдены
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение ключей по вложенности. Т.е., ключи вида <code>"key1/key2/key3" => ["key1", "key2", "key3"]</code>.
|
||||
*
|
||||
* @param string $key Ключ.
|
||||
*
|
||||
* @return array Ключи по вложенности.
|
||||
*/
|
||||
private function ParseKey (string $key): array
|
||||
{
|
||||
// Очищаем ключ
|
||||
$key = $this->PrepareKey($key);
|
||||
|
||||
// Разбиваем ключ на части
|
||||
return explode('/', $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Подготавливает ключ к использованию внутри методов.
|
||||
*
|
||||
* @param string $key Неочищенный ключ.
|
||||
*
|
||||
* @return string Очищенный ключ.
|
||||
*/
|
||||
private function PrepareKey (string $key): string
|
||||
{
|
||||
return trim($key, "/ ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение списка ключей.
|
||||
*
|
||||
* @param string $parentKey Ключ родителя (или "" (установлено по умолчанию) для всех).
|
||||
* @param bool $includeChildren Нужно ли включать дочерние ключи (по умолчанию, да).
|
||||
*
|
||||
* @return array Список ключей.
|
||||
*/
|
||||
public function GetKeys (string $parentKey = "", bool $includeChildren = true): array
|
||||
{
|
||||
// Очищаем ключ
|
||||
$parentKey = $this->PrepareKey($parentKey);
|
||||
|
||||
// Разбиваем ключ на части
|
||||
$keys = StringExtension::IsNullOrWhitespace($parentKey) ? [] : $this->ParseKey($parentKey);
|
||||
|
||||
// Получаем текущий массив данных
|
||||
$current = $this->JsonData;
|
||||
|
||||
// Если ключ не является корневым
|
||||
if (count($keys) > 0)
|
||||
// - переходим к вложенному массиву
|
||||
for ($i = 0; $i < count($keys); $i++)
|
||||
// -- и добавляем массив данных
|
||||
$current = $current[$keys[$i]];
|
||||
|
||||
// Получаем список ключей родителя
|
||||
$parentKeysList = array_keys($current);
|
||||
|
||||
// Если не нужно включать дочерние ключи
|
||||
if (!$includeChildren)
|
||||
// - возвращаем список родительских ключей
|
||||
return $parentKeysList;
|
||||
|
||||
// Создаем результирующий массив
|
||||
$result = [];
|
||||
|
||||
// Для каждого ключа
|
||||
foreach ($parentKeysList as $key) {
|
||||
// - очищаем текущий ключ
|
||||
$currentKey = $this->PrepareKey($parentKey . "/" . $key);
|
||||
|
||||
// - добавляем его в результирующий массив
|
||||
$result[] = $currentKey;
|
||||
|
||||
// - если у текущего ключа есть дочерние ключи
|
||||
if (is_array($current[$key]))
|
||||
// -- добавляем их в результирующий массив
|
||||
$result = array_merge($result, $this->GetKeys($currentKey));
|
||||
}
|
||||
|
||||
// Возвращаем результирующий массив
|
||||
return $result;
|
||||
}
|
||||
}
|
56
sources/traits/JsonReWriter/JsonReWriterLoadSaveTrait.php
Normal file
56
sources/traits/JsonReWriter/JsonReWriterLoadSaveTrait.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\JsonReWriter;
|
||||
|
||||
/**
|
||||
* Часть кода класса JsonReWriter, отвечающая за методы загрузки и сохранения JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
trait JsonReWriterLoadSaveTrait
|
||||
{
|
||||
/**
|
||||
* Сохраняем JSON в файл.
|
||||
*
|
||||
* @param string $fileName Имя файла.
|
||||
*
|
||||
* @return bool Сохранены ли данные в файл: <code>true</code> - да, <code>false</code> - нет.
|
||||
*/
|
||||
public function SaveToFile (string $fileName): bool
|
||||
{
|
||||
// Запись данных в файл
|
||||
return file_put_contents($fileName, $this->JsonString) !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Загрузка данных из JSON-файла.
|
||||
*
|
||||
* @param string $fileName Имя файла.
|
||||
*
|
||||
* @return bool Загрузились ли данные из файла: <code>true</code> - да, <code>false</code> - нет.
|
||||
*/
|
||||
public function LoadFromFile (string $fileName): bool
|
||||
{
|
||||
// Проверка существования файла
|
||||
if (!is_file($fileName))
|
||||
// - если нет, возвращаем false
|
||||
return false;
|
||||
|
||||
// Чтение содержимого файла
|
||||
$result = file_get_contents($fileName);
|
||||
|
||||
// Проверка на ошибки
|
||||
if ($result === false)
|
||||
// - если есть ошибки, возвращаем false
|
||||
return false;
|
||||
|
||||
// Записываем результат
|
||||
$this->JsonString = $result;
|
||||
|
||||
// Возвращаем true, если все хорошо
|
||||
return true;
|
||||
}
|
||||
}
|
173
sources/traits/JsonReWriter/JsonReWriterReadTrait.php
Normal file
173
sources/traits/JsonReWriter/JsonReWriterReadTrait.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\JsonReWriter;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\JsonErrorCode;
|
||||
use goodboyalex\php_components_pack\exceptions\JsonException;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
/**
|
||||
* Часть кода класса JsonReWriter, отвечающая за методы чтения ключей и значений JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
trait JsonReWriterReadTrait
|
||||
{
|
||||
/**
|
||||
* Читает значение ключа JSON как целое число.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param int $default Значение по умолчанию.
|
||||
*
|
||||
* @return int Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadInt (string $key, int $default = 0): int
|
||||
{
|
||||
return (int)$this->Read($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param mixed $default Значение по умолчанию.
|
||||
*
|
||||
* @return mixed Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function Read (string $key, mixed $default = null): mixed
|
||||
{
|
||||
// Подготавливаем ключ
|
||||
$key = $this->PrepareKey($key);
|
||||
|
||||
// Проверяем, существует ли ключ
|
||||
if (!$this->IsKeyExists($key))
|
||||
// - если нет, то возвращаем значение по умолчанию
|
||||
return $default;
|
||||
|
||||
// Разбиваем ключ на массив ключей
|
||||
$keys = $this->ParseKey($key);
|
||||
|
||||
// Получаем текущий массив данных
|
||||
$current = $this->JsonData;
|
||||
|
||||
// Для каждого ключа до предпоследнего
|
||||
for ($i = 0; $i < count($keys) - 1; $i++)
|
||||
// - переходим ко вложенному массиву
|
||||
$current = $current[$keys[$i]];
|
||||
|
||||
// Возвращаем значение последнего ключа и если его нет, то возвращаем значение по умолчанию
|
||||
return $current[$keys[count($keys) - 1]] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как вещественное число.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param float $default Значение по умолчанию.
|
||||
*
|
||||
* @return float Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadFloat (string $key, float $default = 0.0): float
|
||||
{
|
||||
return (float)$this->Read($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как логическое значение.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param bool $default Значение по умолчанию.
|
||||
*
|
||||
* @return bool Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadBool (string $key, bool $default = false): bool
|
||||
{
|
||||
return (bool)$this->Read($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как массив.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param array $default Значение по умолчанию.
|
||||
*
|
||||
* @return array Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadArray (string $key, array $default = []): array
|
||||
{
|
||||
// Получаем значение ключа JSON
|
||||
$serializedDef = json_encode($default);
|
||||
|
||||
// Читаем значение ключа JSON
|
||||
$value = $this->ReadString($key, $serializedDef);
|
||||
|
||||
// Десериализуем значение ключа JSON
|
||||
return json_decode($value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как строку.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param string $default Значение по умолчанию.
|
||||
*
|
||||
* @return string Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadString (string $key, string $default = ""): string
|
||||
{
|
||||
return (string)$this->Read($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как объект.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param object $default Значение по умолчанию.
|
||||
*
|
||||
* @return object Значение ключа JSON или значение по умолчанию.
|
||||
*/
|
||||
public function ReadObject (string $key, object $default): object
|
||||
{
|
||||
// Получаем значение ключа JSON
|
||||
$serializedDef = json_encode($default);
|
||||
|
||||
// Читаем значение ключа JSON
|
||||
$value = $this->ReadString($key, $serializedDef);
|
||||
|
||||
// Десериализуем значение ключа JSON
|
||||
return json_decode($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Читает значение ключа JSON как объект, реализующий интерфейс ISerializable.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param string $serializableClassName Имя класса, реализующего интерфейс ISerializable, с namespace.
|
||||
*
|
||||
* @return ISerializable Инициализированный объект
|
||||
* @throws JsonException Если класс не реализует интерфейс ISerializable
|
||||
*/
|
||||
public function ReadSerializable (string $key, string $serializableClassName): ISerializable
|
||||
{
|
||||
// Создаем объект
|
||||
$instance = new $serializableClassName();
|
||||
|
||||
// Проверяем, что он реализует интерфейс ISerializable
|
||||
if (!$instance instanceof ISerializable)
|
||||
// - если нет, то выбрасываем исключение
|
||||
throw new JsonException(errorCode: JsonErrorCode::NotISerializable,
|
||||
errorMessage: "Class $serializableClassName is not implements ISerializable interface / Класс $serializableClassName не реализует интерфейс ISerializable");
|
||||
|
||||
// Получаем строку JSON из ключа
|
||||
$json = $this->ReadString($key, $instance->Serialize());
|
||||
|
||||
// Десериализуем строку JSON в объект
|
||||
$instance->UnSerialize($json);
|
||||
|
||||
// Возвращаем объект
|
||||
return $instance;
|
||||
}
|
||||
}
|
109
sources/traits/JsonReWriter/JsonReWriterWriteTrait.php
Normal file
109
sources/traits/JsonReWriter/JsonReWriterWriteTrait.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\JsonReWriter;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\JsonErrorCode;
|
||||
use goodboyalex\php_components_pack\exceptions\JsonException;
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
/**
|
||||
* Часть кода класса JsonReWriter, отвечающая за методы записи ключей и значений JSON.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.0
|
||||
*/
|
||||
trait JsonReWriterWriteTrait
|
||||
{
|
||||
/**
|
||||
* Записывает объект в ключ JSON.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param object $value Записываемое значение.
|
||||
*
|
||||
* @return void
|
||||
* @throws JsonException Ключ не содержит вложений, хотя от него требуется обратное.
|
||||
*/
|
||||
public function WriteObject (string $key, object $value): void
|
||||
{
|
||||
$this->Write($key, json_encode($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Записывает значение в ключ JSON.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param mixed $value Записываемое значение.
|
||||
*
|
||||
* @return void
|
||||
* @throws JsonException Ключ не содержит вложений, хотя от него требуется обратное.
|
||||
*/
|
||||
public function Write (string $key, mixed $value): void
|
||||
{
|
||||
// Подготавливаем ключ
|
||||
$key = $this->PrepareKey($key);
|
||||
|
||||
// Получаем массив ключей по вложенности
|
||||
$keys = $this->ParseKey($key);
|
||||
|
||||
// Получаем текущий массив данных
|
||||
$current = &$this->JsonData;
|
||||
|
||||
// Для каждого ключа до предпоследнего
|
||||
for ($i = 0; $i < count($keys) - 1; $i++) {
|
||||
// - проверяем наличие ключа в текущем массиве
|
||||
if (!isset($current[$keys[$i]]))
|
||||
// - нет? Создаем ключ (массив)
|
||||
$current[$keys[$i]] = [];
|
||||
|
||||
// - проверяем, что ключ является массивом
|
||||
if (!is_array($current[$keys[$i]]))
|
||||
// - нет? Выбрасываем исключение
|
||||
throw new JsonException(errorCode: JsonErrorCode::KeyIsNotArray,
|
||||
errorMessage: "The key does not contain attachments, although it is required to do the opposite / Ключ не содержит вложений, хотя от него требуется обратное!");
|
||||
|
||||
// - переходим ко вложенному массиву
|
||||
$current = &$current[$keys[$i]];
|
||||
}
|
||||
|
||||
// Создаем ключ (значение)
|
||||
$current[$keys[count($keys) - 1]] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Записывает объект, реализующий интерфейс ISerializable, в ключ JSON.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param ISerializable $serializableValue Записываемый объект, реализующий интерфейс ISerializable.
|
||||
*
|
||||
* @return void
|
||||
* @throws JsonException Ключ не содержит вложений, хотя от него требуется обратное.
|
||||
*/
|
||||
public function WriteSerializable (string $key, ISerializable $serializableValue): void
|
||||
{
|
||||
// Сериализуем объект
|
||||
$serialized = $serializableValue->Serialize();
|
||||
|
||||
// Записываем в ключ
|
||||
$this->Write($key, $serialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Записывает массив в ключ JSON.
|
||||
*
|
||||
* @param string $key Ключ JSON.
|
||||
* @param array $array Массив для записи.
|
||||
*
|
||||
* @return void
|
||||
* @throws JsonException Ключ не содержит вложений, хотя от него требуется обратное.
|
||||
*/
|
||||
public function WriteArray (string $key, array $array): void
|
||||
{
|
||||
// Сериализуем массив
|
||||
$serialized = json_encode($array);
|
||||
|
||||
// Записываем в ключ
|
||||
$this->Write($key, $serialized);
|
||||
}
|
||||
}
|
@@ -143,6 +143,22 @@ trait ObjectArrayLINQTrait
|
||||
* @return array Ассоциированный массив с результатом выборки.
|
||||
*/
|
||||
public function GetColumn (string $column, ?callable $wherePredicate = null): array
|
||||
{
|
||||
return $this->GetColumnCallback(fn ($item) => property_exists($item, $column) ? $item->$column : null,
|
||||
$wherePredicate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает колонку в массиве данных.
|
||||
*
|
||||
* @param callable $columnPredicate Функция <code>fn (mixed $item): mixed</code>, возвращающая значение элемента
|
||||
* колонки.
|
||||
* @param callable|null $wherePredicate Условие выборки <code>fn (mixed $item): bool</code>, которое проверяет,
|
||||
* подходит элемент или нет.
|
||||
*
|
||||
* @return array Ассоциированный массив с результатом выборки.
|
||||
*/
|
||||
public function GetColumnCallback (callable $columnPredicate, ?callable $wherePredicate = null): array
|
||||
{
|
||||
// Создаю результат
|
||||
$result = [];
|
||||
@@ -153,16 +169,12 @@ trait ObjectArrayLINQTrait
|
||||
if (!is_object($item))
|
||||
continue;
|
||||
|
||||
// - пропускаю не имеющие требуемого свойства
|
||||
if (!property_exists($item, $column))
|
||||
continue;
|
||||
|
||||
// - пропускаю не удовлетворяющие условию
|
||||
if ($wherePredicate !== null && !$wherePredicate($item))
|
||||
continue;
|
||||
|
||||
// - добавляю значение свойства в результат
|
||||
$result[] = $item->$column;
|
||||
$result[] = $columnPredicate($item);
|
||||
}
|
||||
|
||||
// Возвращаю результат
|
||||
@@ -172,7 +184,7 @@ trait ObjectArrayLINQTrait
|
||||
/**
|
||||
* Заменяет данные в строке\ массива.
|
||||
*
|
||||
* @param mixed $setItem Заменяемые элемент.
|
||||
* @param array $setItems Заменяемые элементы.
|
||||
* @param callable $wherePredicate Условие выборки <code>fn (mixed $item): bool</code>, которое проверяет,
|
||||
* подходит элемент или нет.
|
||||
*
|
||||
@@ -184,8 +196,7 @@ trait ObjectArrayLINQTrait
|
||||
$result = $this->Delete($wherePredicate);
|
||||
|
||||
// Добавляю новые элементы
|
||||
foreach ($setItems as $item)
|
||||
$this->Container[] = $item;
|
||||
$this->AddRange($setItems);
|
||||
|
||||
// Возвращаю результат
|
||||
return $result;
|
||||
@@ -280,4 +291,91 @@ trait ObjectArrayLINQTrait
|
||||
// Возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает первый элемент массива или значение по умолчанию.
|
||||
*
|
||||
* @param mixed|null $default Значение по умолчанию. По умолчанию, null.
|
||||
*
|
||||
* @return mixed|null Возвращает первый элемент массива или значение по умолчанию.
|
||||
*/
|
||||
public function First (mixed $default = null): mixed
|
||||
{
|
||||
// Получение первого элемента
|
||||
$firstElement = reset($this->Container);
|
||||
|
||||
// Проверяем получение
|
||||
if ($firstElement === false)
|
||||
// - возвращаем значение по умолчанию
|
||||
return $default;
|
||||
|
||||
// Возвращаем первый элемент
|
||||
return $firstElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает последний элемент массива или значение по умолчанию.
|
||||
*
|
||||
* @param mixed|null $default Значение по умолчанию. По умолчанию, null.
|
||||
*
|
||||
* @return mixed|null Возвращает последний элемент массива или значение по умолчанию.
|
||||
*/
|
||||
public function Last (mixed $default = null): mixed
|
||||
{
|
||||
// Получение последнего элемента
|
||||
$lastElement = end($this->Container);
|
||||
|
||||
// Проверяем получение
|
||||
if ($lastElement === false)
|
||||
// - возвращаем значение по умолчанию
|
||||
return $default;
|
||||
|
||||
// Возвращаем первый элемент
|
||||
return $lastElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Пропускает первые $count элементов массива. Возвращает новый массив.
|
||||
*
|
||||
* ВНИМАНИЕ: рекомендуется использовать ТОЛЬКО на отсортированных массивах.
|
||||
*
|
||||
* @param int $count Количество элементов, которые необходимо обрезать с начала массива.
|
||||
*
|
||||
* @return ObjectArray Возвращает новый массив, состоящий из элементов, начиная с $count + 1 элемента.
|
||||
*/
|
||||
public function Skip (int $count): ObjectArray
|
||||
{
|
||||
return new ObjectArray(array_slice($this->Container, $count));
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает первые $count элементов массива. Возвращает новый массив.
|
||||
*
|
||||
* ВНИМАНИЕ: рекомендуется использовать ТОЛЬКО на отсортированных массивах.
|
||||
*
|
||||
* @param int $count Количество элементов, которые необходимо получить с начала массива.
|
||||
*
|
||||
* @return ObjectArray Возвращает новый массив, состоящий из первых $count элементов старого массива.
|
||||
*/
|
||||
public function Take (int $count): ObjectArray
|
||||
{
|
||||
return new ObjectArray(array_slice($this->Container, 0, $count));
|
||||
}
|
||||
|
||||
/**
|
||||
* Совмещает в себе две функции, которые одновременно применяет к массиву: Skip ($startFrom) и Take ($count).
|
||||
* Возвращает новый массив.
|
||||
*
|
||||
* ВНИМАНИЕ: рекомендуется использовать ТОЛЬКО на отсортированных массивах.
|
||||
*
|
||||
* @param int $startFrom Начальный индекс массива, с которого нужно получить.
|
||||
* @param int $count Количество элементов, которые необходимо получить.
|
||||
*
|
||||
* @return ObjectArray Возвращает новый массив, состоящий из $count элементов старого массива, начиная с индекса
|
||||
* $startFrom.
|
||||
*/
|
||||
public function SkipAndTake (int $startFrom, int $count): ObjectArray
|
||||
{
|
||||
return new ObjectArray(array_slice($this->Container, $startFrom, $count));
|
||||
}
|
||||
}
|
176
sources/traits/ObjectArray/ObjectArraySerializeExTrait.php
Normal file
176
sources/traits/ObjectArray/ObjectArraySerializeExTrait.php
Normal file
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ObjectArray;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||
use goodboyalex\php_components_pack\models\ObjectArraySerializeOptions;
|
||||
|
||||
/**
|
||||
* Часть кода класса ObjectArray, отвечающая за расширенный функции сериализации.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.1.1
|
||||
*/
|
||||
trait ObjectArraySerializeExTrait
|
||||
{
|
||||
/**
|
||||
* Десериализует массив объектов.
|
||||
*
|
||||
* @param string $serialized Сериализованный массив.
|
||||
* @param ObjectArraySerializeOptions|null $options Настройки сериализации. По умолчанию используется настройка по
|
||||
* умолчанию.
|
||||
*
|
||||
* @return ObjectArray Массив объектов.
|
||||
*/
|
||||
public static function UnSerializeEx (string $serialized, ?ObjectArraySerializeOptions $options = null): ObjectArray
|
||||
{
|
||||
// По умолчанию используем настройки по умолчанию
|
||||
$options ??= new ObjectArraySerializeOptions();
|
||||
|
||||
// Десериализуем массив объектов
|
||||
return match ($options->SerializeMethod) {
|
||||
// - стандартный метод UnSerialize
|
||||
ObjectArraySerializeMethod::Serialize => self::UnSerializeBySerialize($serialized),
|
||||
// - метод JsonEncode
|
||||
ObjectArraySerializeMethod::JsonEncode => self::UnSerializeByJsonEncode($serialized),
|
||||
// - метод JsonEncodeWithToArray
|
||||
ObjectArraySerializeMethod::JsonEncodeWithToArray => self::UnSerializeByJsonEncodeWithToArray($serialized,
|
||||
$options->OnClassFrom)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Десериализует массив объектов с помощью стандартного метода UnSerialize.
|
||||
*
|
||||
* @param string $serialized Сериализованный массив.
|
||||
*
|
||||
* @return ObjectArray Массив объектов.
|
||||
*/
|
||||
private static function UnSerializeBySerialize (string $serialized): ObjectArray
|
||||
{
|
||||
// Создаем новый объект
|
||||
$result = new ObjectArray();
|
||||
|
||||
// Десериализуем массив объектов с помощью стандартного метода
|
||||
$result->UnSerialize($serialized);
|
||||
|
||||
// Возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Десериализует массив объектов с помощью метода JsonEncode.
|
||||
*
|
||||
* @param string $serialized Сериализованный массив.
|
||||
*
|
||||
* @return ObjectArray Массив объектов.
|
||||
*/
|
||||
private static function UnSerializeByJsonEncode (string $serialized): ObjectArray
|
||||
{
|
||||
// Десериализуем массив
|
||||
$container = json_decode($serialized, false, flags: JSON_UNESCAPED_UNICODE);
|
||||
|
||||
// Создаем новый объект
|
||||
return new ObjectArray($container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Десериализует массив объектов с помощью метода JsonEncodeWithToArray.
|
||||
*
|
||||
* @param string $serialized Сериализованный массив.
|
||||
* @param callable|null $onClass Функция обратного вызова для десериализации объекта методом JsonEncodeWithToArray.
|
||||
* Она передается в качестве параметра в функцию FromArray и служит для правильного преобразования массива в
|
||||
* тип.
|
||||
*
|
||||
* @return ObjectArray Массив объектов.
|
||||
*/
|
||||
private static function UnSerializeByJsonEncodeWithToArray (string $serialized, ?callable $onClass): ObjectArray
|
||||
{
|
||||
// Десериализуем массив
|
||||
$container = json_decode($serialized, true, flags: JSON_UNESCAPED_UNICODE);
|
||||
|
||||
// Создаем новый объект, в который будем помещать объекты
|
||||
$result = new ObjectArray();
|
||||
|
||||
// Переберем все объекты в контейнере
|
||||
foreach ($container as $item)
|
||||
try {
|
||||
// - пробуем преобразовать массив в объект, если это возможно
|
||||
$result[] = TypeExtension::FromArray($item, $onClass);
|
||||
}
|
||||
catch (TypeException) {
|
||||
// - если не получилось, то просто добавляем объект в массив
|
||||
$result[] = $item;
|
||||
}
|
||||
|
||||
// Возвращаем результат
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сериализует массив объектов.
|
||||
*
|
||||
* @param ObjectArraySerializeOptions|null $options Настройки сериализации. По умолчанию используется настройка по
|
||||
* умолчанию.
|
||||
*
|
||||
* @return string Сериализованный массив.
|
||||
*/
|
||||
public function SerializeEx (?ObjectArraySerializeOptions $options = null): string
|
||||
{
|
||||
// По умолчанию используем настройки по умолчанию
|
||||
$options ??= new ObjectArraySerializeOptions();
|
||||
|
||||
// Сериализуем массив
|
||||
return match ($options->SerializeMethod) {
|
||||
// - стандартный метод Serialize
|
||||
ObjectArraySerializeMethod::Serialize => $this->Serialize(),
|
||||
// - метод JsonEncode
|
||||
ObjectArraySerializeMethod::JsonEncode => $this->SerializeByJsonEncode(),
|
||||
// - метод JsonEncodeWithToArray
|
||||
ObjectArraySerializeMethod::JsonEncodeWithToArray => $this->SerializeByJsonEncodeWithToArray($options->OnClassTo)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Сериализует массив методом JsonEncode.
|
||||
*
|
||||
* @return string Сериализованный массив.
|
||||
*/
|
||||
private function SerializeByJsonEncode (): string
|
||||
{
|
||||
return json_encode($this->Container, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сериализует массив методом JsonEncodeWithToArray.
|
||||
*
|
||||
* @param callable|null $onClass Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray.
|
||||
* Она передается в качестве параметра в функцию ToArray и служит для правильного преобразования типа в массив.
|
||||
*
|
||||
* @return string Сериализованный массив.
|
||||
*/
|
||||
private function SerializeByJsonEncodeWithToArray (?callable $onClass): string
|
||||
{
|
||||
// Создадим массив, в который будем помещать объекты
|
||||
$container = [];
|
||||
|
||||
// Переберем все объекты в контейнере
|
||||
foreach ($this->Container as $item)
|
||||
try {
|
||||
// - пробуем преобразовать объект в массив, если это возможно
|
||||
$container[] = TypeExtension::ToArray($item, $onClass);
|
||||
}
|
||||
catch (TypeException) {
|
||||
// - если не получилось, то просто добавляем объект в массив
|
||||
$container[] = $item;
|
||||
}
|
||||
|
||||
// Возвращаем сериализованный массив
|
||||
return json_encode($container, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
81
sources/traits/ObjectArray/ObjectArraySpecialTrait.php
Normal file
81
sources/traits/ObjectArray/ObjectArraySpecialTrait.php
Normal file
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\traits\ObjectArray;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
|
||||
/**
|
||||
* Часть кода класса ObjectArray, отвечающая за специальные функции.
|
||||
*
|
||||
* @author Александр Бабаев
|
||||
* @package php_components_pack
|
||||
* @version 1.0
|
||||
* @since 1.0
|
||||
*/
|
||||
trait ObjectArraySpecialTrait
|
||||
{
|
||||
/**
|
||||
* Очищает массив объектов, хранящийся в данном классе.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Clear (): void
|
||||
{
|
||||
// Очищаем массив
|
||||
unset($this->Container);
|
||||
|
||||
// Создаем новый массив
|
||||
$this->Container = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет объект в массив объектов, хранящийся в данном классе (аналогично добавлению элемента в массив с
|
||||
* помощью []).
|
||||
*
|
||||
* @param mixed $object Объект, который будет добавлен в массив объектов, хранящийся в данном классе.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Add (mixed $object): void
|
||||
{
|
||||
$this->Container[] = $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет массив объектов (или объекты, заданные с помощью array) в массив объектов, хранящийся в данном классе.
|
||||
*
|
||||
* @param ObjectArray|array $objects Массив объектов, которые будут добавлены в массив объектов.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function AddRange (ObjectArray|array $objects): void
|
||||
{
|
||||
// Если передан массив, то не изменяем его, а если передан объект класса ObjectArray, то конвертируем его в массив объектов
|
||||
$objectsToAdd = is_array($objects) ? $objects : $objects->ToArray();
|
||||
|
||||
// Добавляем массив объектов
|
||||
$this->Merge($objectsToAdd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает массив объектов, хранящихся в данном классе.
|
||||
*
|
||||
* @return array Массив объектов, хранящихся в данном классе.
|
||||
*/
|
||||
public function ToArray (): array
|
||||
{
|
||||
return $this->Container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Объединяет массив объектов, хранящийся в данном классе, с массивом объектов, переданным в качестве параметра.
|
||||
*
|
||||
* @param array $objects Массив объектов, который будет объединен с массивом объектов, хранящимся в данном классе.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function Merge (array $objects): void
|
||||
{
|
||||
$this->Container = array_merge($this->Container, $objects);
|
||||
}
|
||||
}
|
54
tests/classes/ActionStateTest.php
Normal file
54
tests/classes/ActionStateTest.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ActionState;
|
||||
use goodboyalex\php_components_pack\enums\MessageType;
|
||||
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ActionStateTest extends TestCase
|
||||
{
|
||||
public function testActionState (): void
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
$actionState = new ActionState('123');
|
||||
|
||||
$this->assertEquals('123', $actionState->Value);
|
||||
|
||||
$actionState->AddError("Non critical error");
|
||||
$actionState->AddCritical("Critical error");
|
||||
$actionState->AddWarning("Its a warning");
|
||||
|
||||
$this->assertTrue($actionState->HasErrors());
|
||||
$this->assertTrue($actionState->HasErrors(true));
|
||||
$this->assertTrue($actionState->HasWarnings());
|
||||
$this->assertFalse($actionState->IsSuccess());
|
||||
|
||||
$messages = $actionState->GetMessages(ActionState::GET_STRING_ERROR_ONLY());
|
||||
$this->assertEquals(2, $messages->Count());
|
||||
|
||||
$this->assertEquals("Non critical error",
|
||||
$actionState->GetStringMessages(fn (ActionStateMessage $message)
|
||||
=> $message->MessageType
|
||||
== MessageType::Error
|
||||
&& !$message->IsCritical));
|
||||
|
||||
$actionState2 = new ActionState('321');
|
||||
|
||||
$actionState2->AddState($actionState);
|
||||
|
||||
$this->assertEquals(3, $actionState2->Count(ActionState::GET_STRING_ALL()));
|
||||
$this->assertEquals('123', $actionState2->Value);
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/classes/ActionState.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateAddTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateGetTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateHasTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateStaticTrait.php';
|
||||
require_once __DIR__ . '/../../sources/enums/MessageType.php';
|
||||
}
|
||||
}
|
@@ -3,6 +3,8 @@
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ClassMapper;
|
||||
use goodboyalex\php_components_pack\tests\data\A;
|
||||
use goodboyalex\php_components_pack\tests\data\B;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ClassMapperTest extends TestCase
|
||||
@@ -11,12 +13,10 @@ class ClassMapperTest extends TestCase
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$a = new \goodboyalex\php_components_pack\tests\data\A();
|
||||
$a->a = 'a';
|
||||
$a->b = 2;
|
||||
$a->c = true;
|
||||
$a = new A('a', 2, true);
|
||||
|
||||
$b = new B();
|
||||
|
||||
ClassMapper::MapClass($a, $b);
|
||||
|
||||
$this->assertEquals('a', $b->a);
|
||||
@@ -27,6 +27,7 @@ class ClassMapperTest extends TestCase
|
||||
{
|
||||
require_once __DIR__ . '/../data/A.php';
|
||||
require_once __DIR__ . '/../data/B.php';
|
||||
require_once __DIR__ . '/../../sources/attributes/GetOnly.php';
|
||||
require_once __DIR__ . '/../../sources/classes/classMapper.php';
|
||||
}
|
||||
}
|
154
tests/classes/DictionaryTest.php
Normal file
154
tests/classes/DictionaryTest.php
Normal file
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\Dictionary;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class DictionaryTest extends TestCase
|
||||
{
|
||||
public function testRemove ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('2', '2');
|
||||
$dict->Add('3', true);
|
||||
|
||||
$dict->Remove('2');
|
||||
|
||||
$this->assertEquals(1, $dict->Get('1'));
|
||||
$this->assertTrue($dict->Get('3'));
|
||||
$this->assertEquals(2, $dict->count());
|
||||
$this->assertFalse($dict->Has('2'));
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ArrayBasicTrait.php';
|
||||
require_once __DIR__ . '/../../sources/classes/Dictionary.php';
|
||||
}
|
||||
|
||||
public function testGet ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('2', '2');
|
||||
$dict->Add('3', true);
|
||||
|
||||
$this->assertEquals(1, $dict->Get('1'));
|
||||
$this->assertEquals('2', $dict->Get('2'));
|
||||
$this->assertTrue($dict->Get('3'));
|
||||
$this->assertEquals(3, $dict->count());
|
||||
}
|
||||
|
||||
public function testClear ()
|
||||
{
|
||||
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('2', '2');
|
||||
$dict->Add('3', true);
|
||||
$dict->Clear();
|
||||
|
||||
$this->assertEquals(0, $dict->count());
|
||||
}
|
||||
|
||||
public function testAdd ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('2', '2');
|
||||
$dict->Add('3', true);
|
||||
|
||||
$this->assertEquals(1, $dict->Get('1'));
|
||||
$this->assertEquals('2', $dict->Get('2'));
|
||||
$this->assertTrue($dict->Get('3'));
|
||||
$this->assertEquals(3, $dict->count());
|
||||
}
|
||||
|
||||
public function testHas ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('2', '2');
|
||||
$dict->Add('3', true);
|
||||
|
||||
$this->assertTrue($dict->Has('3'));
|
||||
$this->assertFalse($dict->Has('4'));
|
||||
}
|
||||
|
||||
public function testKeys ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('3', true);
|
||||
$dict->Add('2', '2');
|
||||
|
||||
$array = ['1', '3', '2'];
|
||||
|
||||
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($array, $dict->Keys(), []);
|
||||
}
|
||||
|
||||
public function testSort ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('3', true);
|
||||
$dict->Add('2', '2');
|
||||
|
||||
$array = ['1', '2', '3'];
|
||||
|
||||
$dict->Sort();
|
||||
|
||||
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($array, $dict->Keys(), []);
|
||||
}
|
||||
|
||||
public function testAddRange ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
|
||||
$array = ['2' => '2', '3' => true, '4' => false];
|
||||
|
||||
$dict->AddRange($array);
|
||||
|
||||
$this->assertEquals(1, $dict->Get('1'));
|
||||
$this->assertTrue($dict->Get('3'));
|
||||
$this->assertEquals(4, $dict->count());
|
||||
$this->assertFalse($dict->Get("4"));
|
||||
}
|
||||
|
||||
public function testToArray ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$dict = new Dictionary();
|
||||
$dict->Add('1', 1);
|
||||
$dict->Add('3', true);
|
||||
$dict->Add('2', '2');
|
||||
|
||||
$array = $dict->ToArray();
|
||||
|
||||
$this->assertIsArray($array);
|
||||
$this->assertEquals(1, $array['1']);
|
||||
$this->assertTrue($array['3']);
|
||||
$this->assertCount(3, $array);
|
||||
}
|
||||
}
|
87
tests/classes/FileHashTest.php
Normal file
87
tests/classes/FileHashTest.php
Normal file
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\FileHash;
|
||||
use goodboyalex\php_components_pack\enums\HashGetType;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class FileHashTest extends TestCase
|
||||
{
|
||||
public function test__construct ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileHash = new FileHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
||||
$this->assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", $fileHash->Hash);
|
||||
|
||||
|
||||
$fileHash = new FileHash("Тестовое слово", HashGetType::ByString);
|
||||
$this->assertEquals("000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7", $fileHash->Hash);
|
||||
|
||||
$fileHash = new FileHash(__DIR__ . '/../data/A.php', HashGetType::ByFile);
|
||||
$this->assertEquals("fc8dad93af5de5dd7c7d64e04faadfa22557e577a1538737fe462a5f78699fa2", $fileHash->Hash);
|
||||
|
||||
$fileHash = new FileHash(__DIR__ . '/../data/B.php', HashGetType::ByFile);
|
||||
$this->assertEquals("f419262e46e9461517af46d0c1e4faf25f38990bb50351b691d84f1ad51f2299", $fileHash->Hash);
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/traits/EnumExtensionsTrait.php';
|
||||
require_once __DIR__ . '/../../sources/enums/HashGetType.php';
|
||||
require_once __DIR__ . '/../../sources/extensions/StringExtension.php';
|
||||
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
||||
require_once __DIR__ . '/../../sources/classes/FileHash.php';
|
||||
}
|
||||
|
||||
public function testIsEqual ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileHash = new FileHash("Тестовое слово", HashGetType::ByString);
|
||||
|
||||
$this->assertTrue($fileHash->IsEqual(new FileHash("Тестовое слово", HashGetType::ByString)));
|
||||
$this->assertFalse($fileHash->IsEqual(new FileHash("Тестовое слово2", HashGetType::ByString)));
|
||||
}
|
||||
|
||||
public function testSerialize ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileHash = new FileHash("Тестовое слово", HashGetType::ByString);
|
||||
|
||||
$serialized = $fileHash->Serialize();
|
||||
|
||||
$this->assertEquals("s:64:\"000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7\";", $serialized);
|
||||
}
|
||||
|
||||
public function testUnSerialize ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileHash = new FileHash();
|
||||
|
||||
$serialized = "s:64:\"000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7\";";
|
||||
|
||||
$fileHash->UnSerialize($serialized);
|
||||
|
||||
$this->assertEquals("000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7", $fileHash->Hash);
|
||||
}
|
||||
|
||||
public function testValidate ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileHash = new FileHash("Тестовое слово", HashGetType::ByString);
|
||||
|
||||
$this->assertTrue($fileHash->Validate("Тестовое слово", HashGetType::ByString));
|
||||
$this->assertTrue($fileHash->Validate("000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7",
|
||||
HashGetType::ByHash));
|
||||
$this->assertFalse($fileHash->Validate("000e22f7ba01ae35f781bc3069038110c46593306cafef6b489f7c83b34629b7",
|
||||
HashGetType::ByString));
|
||||
|
||||
$fileHash = new FileHash(__DIR__ . '/../data/A.php', HashGetType::ByFile);
|
||||
$this->assertTrue($fileHash->Validate(__DIR__ . '/../data/A.php', HashGetType::ByFile));
|
||||
}
|
||||
}
|
94
tests/classes/FileTest.php
Normal file
94
tests/classes/FileTest.php
Normal file
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\File;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class FileTest extends TestCase
|
||||
{
|
||||
public function testExtractFileName ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals("test.txt", File::ExtractFileName("c:\\tmp\\test.txt"));
|
||||
$this->assertEquals("test.txt", File::ExtractFileName("c:/tmp/test.txt"));
|
||||
$this->assertEquals("test.txt", File::ExtractFileName("\\tmp\\test.txt"));
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/classes/File.php';
|
||||
}
|
||||
|
||||
public function testFindFiles ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$result = File::FindFiles(__DIR__);
|
||||
|
||||
$this->assertIsArray($result);
|
||||
$this->assertCount(8, $result);
|
||||
}
|
||||
|
||||
public function testGetRelativePath ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fullPath = "c:\\source\\tmp\\test.txt";
|
||||
|
||||
$basePath = "c:\\source\\";
|
||||
|
||||
$this->assertEquals("tmp\\test.txt", File::GetRelativePath($fullPath, $basePath));
|
||||
}
|
||||
|
||||
public function testExtractFileExtension ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals("txt", File::ExtractFileExtension("c:\\tmp\\test.txt"));
|
||||
$this->assertEquals("txt", File::ExtractFileExtension("c:/tmp/test.txt"));
|
||||
$this->assertEquals("txt", File::ExtractFileExtension("\\tmp\\test.txt"));
|
||||
}
|
||||
|
||||
public function testExtractFileNameWithoutExtension ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals("test", File::ExtractFileNameWithoutExtension("c:\\tmp\\test.txt"));
|
||||
$this->assertEquals("test", File::ExtractFileNameWithoutExtension("c:/tmp/test.txt"));
|
||||
$this->assertEquals("test", File::ExtractFileNameWithoutExtension("\\tmp\\test.txt"));
|
||||
}
|
||||
|
||||
public function testRemoveDir ()
|
||||
{
|
||||
/**
|
||||
* ВАЖНО! Перед запуском теста необходимо создать директорию D:\TestDelete и наполнить её ненужными файлами
|
||||
*/
|
||||
|
||||
$this->PrepareForTest();
|
||||
|
||||
$result = File::RemoveDir("D:/TestDelete");
|
||||
|
||||
$this->assertTrue($result->Value);
|
||||
$this->assertFalse(File::DirectoryExists("D:\\TestDelete"));
|
||||
}
|
||||
|
||||
public function testFileSize ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$size = File::FileSize("C:\\Windows/explorer.exe");
|
||||
|
||||
$this->assertEquals(2774080, $size->Value);
|
||||
}
|
||||
|
||||
public function testFileSizeString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$size = File::FileSizeToString(2774080);
|
||||
|
||||
$this->assertEquals("2,65 МБ", $size);
|
||||
}
|
||||
}
|
319
tests/classes/JsonReWriterTest.php
Normal file
319
tests/classes/JsonReWriterTest.php
Normal file
@@ -0,0 +1,319 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\File;
|
||||
use goodboyalex\php_components_pack\classes\BoolEx;
|
||||
use goodboyalex\php_components_pack\exceptions\JsonException;
|
||||
use goodboyalex\php_components_pack\tests\data\A;
|
||||
use goodboyalex\php_components_pack\tests\data\C;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class JsonReWriterTest extends TestCase
|
||||
{
|
||||
public function testIsKeyExists ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertTrue($json->IsKeyExists("test/subtest/AAA"));
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/exceptions/JsonException.php';
|
||||
require_once __DIR__ . '/../../sources/traits/JsonReWriter/JsonReWriterDeleteTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/JsonReWriter/JsonReWriterKeyTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/JsonReWriter/JsonReWriterLoadSaveTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/JsonReWriter/JsonReWriterReadTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/JsonReWriter/JsonReWriterWriteTrait.php';
|
||||
require_once __DIR__ . '/../../sources/classes/JsonReWriter.php';
|
||||
require_once __DIR__ . '/../data/A.php';
|
||||
require_once __DIR__ . '/../data/C.php';
|
||||
}
|
||||
|
||||
public function testReadWriteInt ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/test", 123);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertEquals(123, $json->ReadInt("test/test"));
|
||||
}
|
||||
|
||||
public function testReadWriteBool ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/test1", false);
|
||||
$json->Write("test/test2", true);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertTrue($json->ReadBool("test/test2"));
|
||||
$this->assertFalse($json->ReadBool("test/test1"));
|
||||
}
|
||||
|
||||
public function testReadWriteString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/test", "test string");
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertEquals("test string", $json->ReadString("test/test", "test this"));
|
||||
}
|
||||
|
||||
public function testSaveToFile ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
|
||||
if (file_exists($fileName))
|
||||
unlink($fileName);
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$json->SaveToFile($fileName);
|
||||
|
||||
$this->assertFileExists($fileName);
|
||||
|
||||
$size = File::FileSize($fileName)->Value;
|
||||
|
||||
$this->assertEquals(268, $size);
|
||||
|
||||
unlink($fileName);
|
||||
}
|
||||
|
||||
public function testReadWriteArray ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertArrayIsEqualToArrayIgnoringListOfKeys([1, 2, 3], $json->ReadArray("test3/test/res"), []);
|
||||
}
|
||||
|
||||
public function testClear ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$json->Clear();
|
||||
|
||||
$this->assertCount(0, $json->GetKeys());
|
||||
}
|
||||
|
||||
public function testReadWriteObject ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
$class = new A("test", 123, true);
|
||||
|
||||
try {
|
||||
$json->WriteObject("test", $class);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertEquals("test", $json->ReadObject("test", new A())->a);
|
||||
}
|
||||
|
||||
public function testLoadFromFile ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$fileName = __DIR__ . "/test.json";
|
||||
|
||||
if (file_exists($fileName))
|
||||
unlink($fileName);
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$json->SaveToFile($fileName);
|
||||
|
||||
unset($json);
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
$json->LoadFromFile($fileName);
|
||||
|
||||
unlink($fileName);
|
||||
|
||||
$this->assertEquals(123, $json->ReadInt("test1/test"));
|
||||
}
|
||||
|
||||
public function testDeleteKey ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$json->DeleteKey("test3/test/res");
|
||||
|
||||
$this->assertFalse($json->IsKeyExists("test3/test/res"));
|
||||
}
|
||||
|
||||
public function testReadWrite ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->Write("test3/test/res", json_encode([1, 2, 3]));
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertTrue($json->IsKeyExists("test/subtest/AAA"));
|
||||
$this->assertTrue($json->IsKeyExists("test1/test"));
|
||||
$this->assertEquals(1.23, (float)$json->Read("test/subtest/BBB"));
|
||||
}
|
||||
|
||||
public function testGetKeys ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test/subtest/AAA", "123");
|
||||
$json->Write("test/subtest/BBB", 1.23);
|
||||
$json->Write("test1/test", 123);
|
||||
$json->Write("test2/test", true);
|
||||
$json->WriteArray("test3/test/res", [1, 2, 3]);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertCount(11, $json->GetKeys());
|
||||
$this->assertCount(2, $json->GetKeys("test/subtest"));
|
||||
}
|
||||
|
||||
public function testReadWriteSerializable ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$serializableClass = new C("test", 123, true);
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->WriteSerializable("test", $serializableClass);
|
||||
|
||||
/**
|
||||
* @var C $unSerializableClass Получаем объект из файла
|
||||
*/
|
||||
$unSerializableClass = $json->ReadSerializable("test", "goodboyalex\\php_components_pack\\tests\\data\\C");
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
$this->assertEquals($serializableClass->stringC, $unSerializableClass->stringC);
|
||||
$this->assertEquals($serializableClass->intC, $unSerializableClass->intC);
|
||||
$this->assertEquals($serializableClass->boolC, $unSerializableClass->boolC);
|
||||
}
|
||||
|
||||
public function testReadWriteFloat ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$json = new BoolEx();
|
||||
try {
|
||||
$json->Write("test", 1.23);
|
||||
}
|
||||
catch (JsonException $e) {
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
$this->assertEquals(1.23, $json->ReadFloat("test", 0.2));
|
||||
}
|
||||
}
|
@@ -3,8 +3,14 @@
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||
use goodboyalex\php_components_pack\models\ObjectArraySerializeOptions;
|
||||
use goodboyalex\php_components_pack\tests\data\A;
|
||||
use goodboyalex\php_components_pack\tests\data\B;
|
||||
use goodboyalex\php_components_pack\tests\data\C;
|
||||
use goodboyalex\php_components_pack\tests\data\D;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use stdClass;
|
||||
|
||||
class ObjectArrayTest extends TestCase
|
||||
{
|
||||
@@ -38,11 +44,14 @@ class ObjectArrayTest extends TestCase
|
||||
{
|
||||
require_once __DIR__ . '/../data/A.php';
|
||||
require_once __DIR__ . '/../data/B.php';
|
||||
require_once __DIR__ . '/../data/C.php';
|
||||
require_once __DIR__ . '/../data/D.php';
|
||||
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArrayBasicTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ArrayBasicTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArrayConstantsTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArrayLINQTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArraySearchAndSortTrait.php';
|
||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArraySpecialTrait.php';
|
||||
require_once __DIR__ . '/../../sources/classes/ObjectArray.php';
|
||||
}
|
||||
|
||||
@@ -312,4 +321,233 @@ class ObjectArrayTest extends TestCase
|
||||
$this->assertEquals('a', $sr->a);
|
||||
$this->assertTrue($sr->c);
|
||||
}
|
||||
|
||||
public function testFirst ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray($array);
|
||||
|
||||
$sr = $a_Array->First();
|
||||
|
||||
$this->assertNotNull($sr);
|
||||
$this->assertInstanceOf(A::class, $sr);
|
||||
$this->assertEquals('a', $sr->a);
|
||||
$this->assertTrue($sr->c);
|
||||
}
|
||||
|
||||
public function testLast ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray($array);
|
||||
|
||||
$sr = $a_Array->Last();
|
||||
|
||||
$this->assertNotNull($sr);
|
||||
$this->assertInstanceOf(A::class, $sr);
|
||||
$this->assertEquals('b', $sr->a);
|
||||
$this->assertTrue($sr->c);
|
||||
}
|
||||
|
||||
public function testSkip ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
new A("d", 5, true),
|
||||
new A("e", 4, true),
|
||||
new A("f", 6, false)
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray($array);
|
||||
|
||||
// Для начала отсортируем по b
|
||||
$a_Array->Sort("b");
|
||||
|
||||
$b_Array = $a_Array->Skip(2);
|
||||
|
||||
$this->assertNotNull($b_Array);
|
||||
$this->assertEquals(4, $b_Array->Count());
|
||||
$this->assertEquals(3, $b_Array->First()->b);
|
||||
$this->assertEquals(6, $b_Array->Last()->b);
|
||||
}
|
||||
|
||||
public function testTake ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
new A("d", 5, true),
|
||||
new A("e", 4, true),
|
||||
new A("f", 6, false)
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray($array);
|
||||
|
||||
// Для начала отсортируем по b
|
||||
$a_Array->Sort("b");
|
||||
|
||||
$b_Array = $a_Array->Take(3);
|
||||
|
||||
$this->assertNotNull($b_Array);
|
||||
$this->assertEquals(3, $b_Array->Count());
|
||||
$this->assertEquals(1, $b_Array->First()->b);
|
||||
$this->assertEquals(3, $b_Array->Last()->b);
|
||||
}
|
||||
|
||||
public function testSkipAndTake ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
new A("d", 5, true),
|
||||
new A("e", 4, true),
|
||||
new A("f", 6, false)
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray($array);
|
||||
|
||||
// Для начала отсортируем по b
|
||||
$a_Array->Sort("b");
|
||||
|
||||
$b_Array = $a_Array->SkipAndTake(2, 3);
|
||||
|
||||
$this->assertNotNull($b_Array);
|
||||
$this->assertEquals(3, $b_Array->Count());
|
||||
$this->assertEquals(3, $b_Array->First()->b);
|
||||
$this->assertEquals(5, $b_Array->Last()->b);
|
||||
}
|
||||
|
||||
public function testAdd ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$obj = new A("a", 3, true);
|
||||
|
||||
$a_Array = new ObjectArray([]);
|
||||
|
||||
$a_Array->Add($obj);
|
||||
|
||||
$b_Array = $a_Array->GetRow(fn (A $a) => $a->a == "a");
|
||||
|
||||
$this->assertEquals(3, $b_Array->b);
|
||||
}
|
||||
|
||||
public function testAddRange ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
new A("a", 3, true),
|
||||
new A("c", 2, false),
|
||||
new A("b", 1, true),
|
||||
new A("d", 5, true),
|
||||
new A("e", 4, true),
|
||||
new A("f", 6, false)
|
||||
];
|
||||
|
||||
$a_Array = new ObjectArray();
|
||||
$a_Array->AddRange($array);
|
||||
|
||||
$this->assertEquals(6, $a_Array->Count());
|
||||
|
||||
$array2 = [
|
||||
new A("g", 3, true),
|
||||
new A("h", 2, false),
|
||||
new A("i", 1, true),
|
||||
new A("k", 5, true),
|
||||
new A("l", 4, true),
|
||||
new A("m", 6, false)
|
||||
];
|
||||
|
||||
$objectArray = new ObjectArray($array2);
|
||||
|
||||
$a_Array->AddRange($objectArray);
|
||||
|
||||
$this->assertEquals(12, $a_Array->Count());
|
||||
}
|
||||
|
||||
public function testSerializeEx ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
// Создаём тестовые классы
|
||||
$class1 = new D ('test_string1', 12345, true, new A("test_string_A1", 6789, false),
|
||||
new B("test_string_B1", 9876, "false"), new C("test_string_C1", 54321, true));
|
||||
$class2 = new D ('test_string2', 123456, false, new A("test_string_A1", 678910, true),
|
||||
new B("test_string_B2", 98765, "true"), new C("test_string_C2", 543210, false));
|
||||
$class = new D ('test_string3', 123450, true, new A("test_string_A2", 67890, false),
|
||||
new B("test_string_B3", 90876, "false"), new C("test_string_C3", 543201, true));
|
||||
|
||||
// Создаём массив объектов
|
||||
$objectArray = new ObjectArray([$class1, $class2, $class]);
|
||||
|
||||
// Сериализуем
|
||||
$serialized1 =
|
||||
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::Serialize));
|
||||
$serialized2 =
|
||||
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncode));
|
||||
$serialized3 =
|
||||
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncodeWithToArray,
|
||||
D::CLOSURE_TO_ARRAY()));
|
||||
|
||||
// Сохраняем в файл
|
||||
file_put_contents(__DIR__ . 'serialized1.txt', $serialized1);
|
||||
file_put_contents(__DIR__ . 'serialized2.txt', $serialized2);
|
||||
file_put_contents(__DIR__ . 'serialized3.txt', $serialized3);
|
||||
|
||||
// Проверяем, что всё хорошо
|
||||
$this->assertNotEmpty($serialized1);
|
||||
$this->assertNotEmpty($serialized2);
|
||||
$this->assertNotEmpty($serialized3);
|
||||
}
|
||||
|
||||
public function testUnSerializeEx ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
// Загружаем данные
|
||||
$serialized1 = file_get_contents(__DIR__ . 'serialized1.txt');
|
||||
$serialized2 = file_get_contents(__DIR__ . 'serialized2.txt');
|
||||
$serialized3 = file_get_contents(__DIR__ . 'serialized3.txt');
|
||||
|
||||
// Десериализуем
|
||||
$objectArray1 = ObjectArray::UnSerializeEx($serialized1,
|
||||
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::Serialize));
|
||||
$objectArray2 = ObjectArray::UnSerializeEx($serialized2,
|
||||
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncode));
|
||||
$objectArray3 = ObjectArray::UnSerializeEx($serialized3,
|
||||
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncodeWithToArray,
|
||||
onClassFrom: D::CLOSURE_FROM_ARRAY()));
|
||||
|
||||
// Проверяем, что всё хорошо
|
||||
$this->assertEquals('test_string_A1',
|
||||
$objectArray1->GetRow(fn (D $value) => $value->stringD == 'test_string1')->a->a);
|
||||
$this->assertEquals('test_string_B2',
|
||||
$objectArray2->GetRow(fn (stdClass $value) => $value->stringD == 'test_string2')->b->a);
|
||||
$this->assertEquals('test_string_C3',
|
||||
$objectArray3->GetRow(fn (D $value) => $value->stringD == 'test_string3')->c->stringC);
|
||||
}
|
||||
}
|
37
tests/classes/TupleTest.php
Normal file
37
tests/classes/TupleTest.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\classes\Tuple;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class TupleTest extends TestCase
|
||||
{
|
||||
public function testTuple ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$tuple = new Tuple(1, 'string', ['array1', 'array2', 'array3']);
|
||||
|
||||
// Проверка на то, что возвращает значение кортежа при запросе значения по индексу
|
||||
$this->assertEquals(1, $tuple->Get(0));
|
||||
$this->assertEquals('string', $tuple->Get(1));
|
||||
$this->assertEquals(['array1', 'array2', 'array3'], $tuple->Get(2));
|
||||
|
||||
// Проверка на то, что возвращает переменные
|
||||
[$firstElement, $secondElement, $thirdElement] = $tuple;
|
||||
$this->assertEquals(1, $firstElement);
|
||||
$this->assertEquals('string', $secondElement);
|
||||
$this->assertEquals(['array1', 'array2', 'array3'], $thirdElement);
|
||||
|
||||
// Проверка на то, что выбрасывает исключение при попытке задать данные в кортеж после его создания
|
||||
$this->expectException(Exception::class);
|
||||
$tuple[] = 'New data';
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/classes/Tuple.php';
|
||||
}
|
||||
}
|
66
tests/classes/TwoDimSizeTest.php
Normal file
66
tests/classes/TwoDimSizeTest.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use Exception;
|
||||
use goodboyalex\php_components_pack\classes\TwoDimSize;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class TwoDimSizeTest extends TestCase
|
||||
{
|
||||
public function testParse ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
try {
|
||||
$size = TwoDimSize::Parse("10x20", "x");
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$this->fail($e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertEquals(10, $size->Width);
|
||||
$this->assertEquals(20, $size->Height);
|
||||
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
||||
require_once __DIR__ . '/../../sources/classes/TwoDimSize.php';
|
||||
}
|
||||
|
||||
public function test__toString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$size = new TwoDimSize(10, 20);
|
||||
|
||||
$this->assertEquals("10:20", $size->__toString());
|
||||
}
|
||||
|
||||
public function testSerialize ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$size = new TwoDimSize(10, 20);
|
||||
|
||||
$this->assertEquals("10x20x1", $size->Serialize());
|
||||
|
||||
}
|
||||
|
||||
public function testUnSerialize ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$serialized = "10x20x1";
|
||||
|
||||
$size = new TwoDimSize();
|
||||
|
||||
$size->UnSerialize($serialized);
|
||||
|
||||
$this->assertEquals(10, $size->Width);
|
||||
$this->assertEquals(20, $size->Height);
|
||||
$this->assertTrue($size->NoNegativeValues);
|
||||
}
|
||||
}
|
134
tests/classes/VersionInfoTest.php
Normal file
134
tests/classes/VersionInfoTest.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
|
||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||
use goodboyalex\php_components_pack\classes\VersionInfo;
|
||||
use goodboyalex\php_components_pack\enums\VersionInfoStage;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class VersionInfoTest extends TestCase
|
||||
{
|
||||
public function testCompareWith ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$versionInfo1 = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
$versionInfo2 = new VersionInfo(1, 1, 3, 4, VersionInfoStage::Alpha, 2);
|
||||
|
||||
$this->assertEquals(1, $versionInfo1->CompareWith($versionInfo2));
|
||||
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/enums/VersionInfoStage.php';
|
||||
require_once __DIR__ . '/../../sources/classes/VersionInfo.php';
|
||||
}
|
||||
|
||||
public function test__toString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
$versionInfo = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
$this->assertEquals('1.2.3.4 Beta 1', $versionInfo->__toString());
|
||||
}
|
||||
|
||||
public function testToString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
$versionInfo = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
|
||||
$template = "Это #{Stage} #{StageNumber} версии #{Major}.#{Minor}.#{Release}.#{Build}";
|
||||
|
||||
$stageNames = [
|
||||
VersionInfoStage::PreAlpha->value => 'рано',
|
||||
VersionInfoStage::Alpha->value => 'начало',
|
||||
VersionInfoStage::Beta->value => 'середнячок',
|
||||
VersionInfoStage::ReleaseCandidate->value => 'почти',
|
||||
VersionInfoStage::Stable->value => 'это релиз, детка!'
|
||||
];
|
||||
|
||||
$this->assertEquals('Это середнячок 1 версии 1.2.3.4', $versionInfo->ToString($template, $stageNames));
|
||||
}
|
||||
|
||||
public function testParse ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$stageNames = [
|
||||
VersionInfoStage::PreAlpha->value => 'pre',
|
||||
VersionInfoStage::Alpha->value => 'alpha',
|
||||
VersionInfoStage::Beta->value => 'beta',
|
||||
VersionInfoStage::ReleaseCandidate->value => 'rc',
|
||||
VersionInfoStage::Stable->value => 'stable'
|
||||
];
|
||||
|
||||
$version = VersionInfo::Parse('1.2.3.4 beta 1', $stageNames);
|
||||
|
||||
$this->assertEquals(1, $version->Major);
|
||||
$this->assertEquals(2, $version->Minor);
|
||||
$this->assertEquals(3, $version->Release);
|
||||
$this->assertEquals(4, $version->Build);
|
||||
$this->assertEquals(VersionInfoStage::Beta, $version->Stage);
|
||||
$this->assertEquals(1, $version->StageNumber);
|
||||
}
|
||||
|
||||
public function test__construct ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$version = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
|
||||
$this->assertEquals(2, $version->Minor);
|
||||
}
|
||||
|
||||
public function testCompare ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$versionInfo1 = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
$versionInfo2 = new VersionInfo(1, 1, 3, 4, VersionInfoStage::Alpha, 2);
|
||||
|
||||
$this->assertEquals(1, VersionInfo::Compare($versionInfo1, $versionInfo2));
|
||||
}
|
||||
|
||||
public function testCompareWithRange ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$versionInfo1 = new VersionInfo(1, 2, 3, 4, VersionInfoStage::Beta, 1);
|
||||
|
||||
$versionInfo2 = new VersionInfo(1, 1, 3, 4, VersionInfoStage::Alpha, 2);
|
||||
|
||||
$versionInfo3 = new VersionInfo(1, 1, 1, 1, VersionInfoStage::Alpha, 2);
|
||||
|
||||
$versionInfo4 = new VersionInfo(5, 5, 5, 5, VersionInfoStage::Stable);
|
||||
|
||||
$optionNotBorder = new ObjectArray();
|
||||
|
||||
// Для начала простое сравнение
|
||||
$this->assertEquals(0, $versionInfo1->CompareWithRange($versionInfo3, $versionInfo4));
|
||||
$this->assertEquals(-1, $versionInfo2->CompareWithRange($versionInfo1, $versionInfo4));
|
||||
$this->assertEquals(1, $versionInfo4->CompareWithRange($versionInfo2, $versionInfo1));
|
||||
|
||||
// Немного перепутаем границы =)
|
||||
$this->assertEquals(1, $versionInfo4->CompareWithRange($versionInfo1, $versionInfo2));
|
||||
|
||||
// А теперь с границами
|
||||
// - значение равно левой границе
|
||||
$this->assertEquals(0, $versionInfo2->CompareWithRange($versionInfo2, $versionInfo1));
|
||||
// - значение равно правой границе
|
||||
$this->assertEquals(0, $versionInfo1->CompareWithRange($versionInfo2, $versionInfo1));
|
||||
// - а теперь с выключением границ
|
||||
// -- для левой
|
||||
$this->assertEquals(-1, $versionInfo2->CompareWithRange($versionInfo2, $versionInfo1, $optionNotBorder));
|
||||
// -- для правой
|
||||
$this->assertEquals(1, $versionInfo1->CompareWithRange($versionInfo2, $versionInfo1, $optionNotBorder));
|
||||
|
||||
// А что если границы равны и значение равно
|
||||
// - для включённых границ
|
||||
$this->assertEquals(0, $versionInfo1->CompareWithRange($versionInfo1, $versionInfo1));
|
||||
// - для выключённых границ
|
||||
$this->assertEquals(-1, $versionInfo1->CompareWithRange($versionInfo1, $versionInfo1, $optionNotBorder));
|
||||
}
|
||||
}
|
@@ -1,10 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\classes;
|
||||
namespace goodboyalex\php_components_pack\tests\data;
|
||||
|
||||
class B
|
||||
{
|
||||
public string $a;
|
||||
public int $b;
|
||||
public string $d;
|
||||
|
||||
public function __construct (string $a = "", int $b = 0, string $d = "")
|
||||
{
|
||||
$this->a = $a;
|
||||
$this->b = $b;
|
||||
$this->d = $d;
|
||||
}
|
||||
}
|
36
tests/data/C.php
Normal file
36
tests/data/C.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\data;
|
||||
|
||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||
|
||||
class C implements ISerializable
|
||||
{
|
||||
public string $stringC;
|
||||
public int $intC;
|
||||
public bool $boolC;
|
||||
|
||||
public function __construct (string $string = "", int $int = 0, bool $bool = false)
|
||||
{
|
||||
$this->stringC = $string;
|
||||
$this->intC = $int;
|
||||
$this->boolC = $bool;
|
||||
}
|
||||
|
||||
public function Serialize (): string
|
||||
{
|
||||
$array = [];
|
||||
$array["string"] = $this->stringC;
|
||||
$array["int"] = $this->intC;
|
||||
$array["bool"] = $this->boolC;
|
||||
return json_encode($array);
|
||||
}
|
||||
|
||||
public function UnSerialize (string $serialized): void
|
||||
{
|
||||
$array = json_decode($serialized, true);
|
||||
$this->stringC = $array["string"];
|
||||
$this->intC = $array["int"];
|
||||
$this->boolC = $array["bool"];
|
||||
}
|
||||
}
|
56
tests/data/D.php
Normal file
56
tests/data/D.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\data;
|
||||
|
||||
use Closure;
|
||||
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||
|
||||
class D
|
||||
{
|
||||
public string $stringD;
|
||||
public int $intD;
|
||||
public bool $boolD;
|
||||
public A $a;
|
||||
public B $b;
|
||||
public C $c;
|
||||
|
||||
public function __construct (string $string = "", int $int = 0, bool $bool = false, ?A $a = null, ?B $b = null,
|
||||
?C $c = null)
|
||||
{
|
||||
$this->stringD = $string;
|
||||
$this->intD = $int;
|
||||
$this->boolD = $bool;
|
||||
|
||||
$this->a = $a ?? new A();
|
||||
$this->b = $b ?? new B();
|
||||
$this->c = $c ?? new C();
|
||||
}
|
||||
|
||||
public static function CLOSURE_FROM_ARRAY (): Closure
|
||||
{
|
||||
return fn (array $classArray): object
|
||||
=> $classArray['type_class'] == C::class
|
||||
? self::CLOSURE_FROM_FOR_C($classArray["type_value"]) : TypeExtension::FromArray($classArray);
|
||||
}
|
||||
|
||||
private static function CLOSURE_FROM_FOR_C (string $serializedC): object
|
||||
{
|
||||
$classC = new C();
|
||||
$classC->UnSerialize($serializedC);
|
||||
return $classC;
|
||||
}
|
||||
|
||||
public static function CLOSURE_TO_ARRAY (): Closure
|
||||
{
|
||||
return fn (object $class): array => $class instanceof C ? self::CLOSURE_TO_FOR_C($class)
|
||||
: TypeExtension::ToArray($class);
|
||||
}
|
||||
|
||||
private static function CLOSURE_TO_FOR_C (C $class): array
|
||||
{
|
||||
return [
|
||||
"type_class" => C::class,
|
||||
"type_value" => $class->Serialize()
|
||||
];
|
||||
}
|
||||
}
|
65
tests/extensions/BoolExtensionsTest.php
Normal file
65
tests/extensions/BoolExtensionsTest.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\extensions;
|
||||
|
||||
use goodboyalex\php_components_pack\enums\VarNotBoolAction;
|
||||
use goodboyalex\php_components_pack\extensions\BoolExtensions;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class BoolExtensionsTest extends TestCase
|
||||
{
|
||||
public function testAnyTrue ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$hasTrue = [
|
||||
true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false,
|
||||
true, false, true, false, true, false, true, false, true, false, true, false
|
||||
];
|
||||
|
||||
$noTrue = [
|
||||
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
|
||||
false, false, false, false, false, false, false, false, false, false, false
|
||||
];
|
||||
|
||||
$this->assertTrue(BoolExtensions::AnyTrue($hasTrue));
|
||||
|
||||
$this->assertFalse(BoolExtensions::AnyTrue($noTrue));
|
||||
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/enums/VarNotBoolAction.php';
|
||||
require_once __DIR__ . '/../../sources/extensions/BoolExtensions.php';
|
||||
}
|
||||
|
||||
public function testTrueCount ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$array = [
|
||||
true, false, true, false, true, false, true, false, true, false, true, false,
|
||||
true, false, true, false, true, false, true, false, true, false, true, false, true, false, true,
|
||||
false
|
||||
];
|
||||
|
||||
$this->assertEquals(14,
|
||||
BoolExtensions::TrueCount($array));
|
||||
|
||||
$array[] = "ПРЕДАТЕЛЬ!";
|
||||
|
||||
$this->assertEquals(14, BoolExtensions::TrueCount($array));
|
||||
$this->assertEquals(14, BoolExtensions::TrueCount($array, VarNotBoolAction::ConsiderItFalse));
|
||||
$this->assertEquals(15, BoolExtensions::TrueCount($array, VarNotBoolAction::ConsiderItTrue));
|
||||
}
|
||||
|
||||
public function testExportToString ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals('О, да!', BoolExtensions::ExportToString(true, 'О, да!', 'О, нет!'));
|
||||
|
||||
$this->assertEquals('О, нет!', BoolExtensions::ExportToString(false, 'О, да!', 'О, нет!'));
|
||||
}
|
||||
}
|
@@ -63,4 +63,20 @@ class StringExtensionTest extends TestCase
|
||||
$this->assertEquals('', StringExtension::GetShortText('test', 0));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public function testReplace ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals('Все 2 ночи и 2 дня 2 друга искали тебя!',
|
||||
StringExtension::Replace("4", "2", "Все 4 ночи и 4 дня 2 друга искали тебя!"));
|
||||
}
|
||||
|
||||
public function testReplaceAll ()
|
||||
{
|
||||
$this->PrepareForTest();
|
||||
|
||||
$this->assertEquals('Все 5 ночи и 5 дня 2 друга искали тебя!',
|
||||
StringExtension::ReplaceAll(["4" => "5", "3" => "2"], "Все 4 ночи и 4 дня 3 друга искали тебя!"));
|
||||
}
|
||||
}
|
91
tests/extensions/TypeExtensionTest.php
Normal file
91
tests/extensions/TypeExtensionTest.php
Normal file
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace goodboyalex\php_components_pack\tests\extensions;
|
||||
|
||||
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||
use goodboyalex\php_components_pack\tests\data\A;
|
||||
use goodboyalex\php_components_pack\tests\data\B;
|
||||
use goodboyalex\php_components_pack\tests\data\C;
|
||||
use goodboyalex\php_components_pack\tests\data\D;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class TypeExtensionTest extends TestCase
|
||||
{
|
||||
public function testFromArray ()
|
||||
{
|
||||
// Подготавливаем данные к тестированию
|
||||
$this->PrepareForTest();
|
||||
|
||||
// Зададим имя файла
|
||||
$fileName = __DIR__ . "/class.txt";
|
||||
|
||||
// Если файл не найден
|
||||
if (!file_exists($fileName))
|
||||
// - то завершаем работу
|
||||
die("The test data file could not be found or has not yet passed the ToArray test! / Файл с данными для тестирования не найден или не пройдено ещё тестирование ToArray!");
|
||||
|
||||
// Считываем данные из файла и преобразуем в массив
|
||||
$array = json_decode(file_get_contents($fileName), true);
|
||||
|
||||
// Преобразуем в объект
|
||||
try {
|
||||
$class = TypeExtension::FromArray($array, D::CLOSURE_FROM_ARRAY());
|
||||
}
|
||||
catch (TypeException $e) {
|
||||
// - если ошибка, то выводим её и завершаем работу
|
||||
die($e->getMessage());
|
||||
}
|
||||
|
||||
// Проверяем
|
||||
$this->assertEquals(D::class, $class::class);
|
||||
$this->assertEquals(A::class, $class->a::class);
|
||||
$this->assertEquals(B::class, $class->b::class);
|
||||
$this->assertEquals(9876, $class->b->b);
|
||||
$this->assertEquals(C::class, $class->c::class);
|
||||
$this->assertEquals(54321, $class->c->intC);
|
||||
$this->assertEquals('test_string', $class->stringD);
|
||||
}
|
||||
|
||||
private function PrepareForTest (): void
|
||||
{
|
||||
require_once __DIR__ . '/../../sources/exceptions/TypeException.php';
|
||||
require_once __DIR__ . '/../../sources/extensions/TypeExtension.php';
|
||||
require_once __DIR__ . '/../data/A.php';
|
||||
require_once __DIR__ . '/../data/B.php';
|
||||
require_once __DIR__ . '/../data/C.php';
|
||||
require_once __DIR__ . '/../data/D.php';
|
||||
}
|
||||
|
||||
public function testToArray ()
|
||||
{
|
||||
// Подготавливаем данные к тестированию
|
||||
$this->PrepareForTest();
|
||||
|
||||
// Создаём тестовый класс
|
||||
$class = new D ('test_string', 12345, true, new A("test_string_A", 6789, false),
|
||||
new B("test_string_B", 9876, "false"), new C("test_string_C", 54321, true));
|
||||
|
||||
// Преобразуем в массив
|
||||
try {
|
||||
$array = TypeExtension::ToArray($class, D::CLOSURE_TO_ARRAY());
|
||||
}
|
||||
catch (TypeException $e) {
|
||||
// - если ошибка, то выводим её и завершаем работу
|
||||
die($e->getMessage());
|
||||
}
|
||||
|
||||
// Сохраняем массив в файл (для тестирования FromArray)
|
||||
file_put_contents(__DIR__ . "/class.txt", json_encode($array, JSON_PRETTY_PRINT));
|
||||
|
||||
// Проверяем
|
||||
$this->assertEquals(D::class, $array['type_class']);
|
||||
$this->assertEquals(A::class, $array['a']['type_class']);
|
||||
$this->assertEquals(B::class, $array['b']['type_class']);
|
||||
$this->assertEquals(9876, $array['b']['b']);
|
||||
$this->assertEquals(C::class, $array['c']['type_class']);
|
||||
$this->assertEquals('test_string', $array['stringD']);
|
||||
$this->assertEquals(12345, $array['intD']);
|
||||
$this->assertTrue($array['boolD']);
|
||||
}
|
||||
}
|
25
vendor/autoload.php
vendored
25
vendor/autoload.php
vendored
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
// autoload.php @generated by Composer
|
||||
|
||||
if (PHP_VERSION_ID < 50600) {
|
||||
if (!headers_sent()) {
|
||||
header('HTTP/1.1 500 Internal Server Error');
|
||||
}
|
||||
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
|
||||
if (!ini_get('display_errors')) {
|
||||
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||
fwrite(STDERR, $err);
|
||||
} elseif (!headers_sent()) {
|
||||
echo $err;
|
||||
}
|
||||
}
|
||||
trigger_error(
|
||||
$err,
|
||||
E_USER_ERROR
|
||||
);
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/composer/autoload_real.php';
|
||||
|
||||
return ComposerAutoloaderInitc00e5b601adae61bbbc3f6be4864ef55::getLoader();
|
119
vendor/bin/php-parse
vendored
119
vendor/bin/php-parse
vendored
@@ -1,119 +0,0 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Proxy PHP file generated by Composer
|
||||
*
|
||||
* This file includes the referenced bin path (../nikic/php-parser/bin/php-parse)
|
||||
* using a stream wrapper to prevent the shebang from being output on PHP<8
|
||||
*
|
||||
* @generated
|
||||
*/
|
||||
|
||||
namespace Composer;
|
||||
|
||||
$GLOBALS['_composer_bin_dir'] = __DIR__;
|
||||
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
|
||||
|
||||
if (PHP_VERSION_ID < 80000) {
|
||||
if (!class_exists('Composer\BinProxyWrapper')) {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class BinProxyWrapper
|
||||
{
|
||||
private $handle;
|
||||
private $position;
|
||||
private $realpath;
|
||||
|
||||
public function stream_open($path, $mode, $options, &$opened_path)
|
||||
{
|
||||
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
|
||||
$opened_path = substr($path, 17);
|
||||
$this->realpath = realpath($opened_path) ?: $opened_path;
|
||||
$opened_path = $this->realpath;
|
||||
$this->handle = fopen($this->realpath, $mode);
|
||||
$this->position = 0;
|
||||
|
||||
return (bool) $this->handle;
|
||||
}
|
||||
|
||||
public function stream_read($count)
|
||||
{
|
||||
$data = fread($this->handle, $count);
|
||||
|
||||
if ($this->position === 0) {
|
||||
$data = preg_replace('{^#!.*\r?\n}', '', $data);
|
||||
}
|
||||
|
||||
$this->position += strlen($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function stream_cast($castAs)
|
||||
{
|
||||
return $this->handle;
|
||||
}
|
||||
|
||||
public function stream_close()
|
||||
{
|
||||
fclose($this->handle);
|
||||
}
|
||||
|
||||
public function stream_lock($operation)
|
||||
{
|
||||
return $operation ? flock($this->handle, $operation) : true;
|
||||
}
|
||||
|
||||
public function stream_seek($offset, $whence)
|
||||
{
|
||||
if (0 === fseek($this->handle, $offset, $whence)) {
|
||||
$this->position = ftell($this->handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function stream_tell()
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function stream_eof()
|
||||
{
|
||||
return feof($this->handle);
|
||||
}
|
||||
|
||||
public function stream_stat()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
public function stream_set_option($option, $arg1, $arg2)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function url_stat($path, $flags)
|
||||
{
|
||||
$path = substr($path, 17);
|
||||
if (file_exists($path)) {
|
||||
return stat($path);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
(function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
|
||||
|| (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
|
||||
) {
|
||||
return include("phpvfscomposer://" . __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse');
|
||||
}
|
||||
}
|
||||
|
||||
return include __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse';
|
5
vendor/bin/php-parse.bat
vendored
5
vendor/bin/php-parse.bat
vendored
@@ -1,5 +0,0 @@
|
||||
@ECHO OFF
|
||||
setlocal DISABLEDELAYEDEXPANSION
|
||||
SET BIN_TARGET=%~dp0/php-parse
|
||||
SET COMPOSER_RUNTIME_BIN_DIR=%~dp0
|
||||
php "%BIN_TARGET%" %*
|
122
vendor/bin/phpunit
vendored
122
vendor/bin/phpunit
vendored
@@ -1,122 +0,0 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Proxy PHP file generated by Composer
|
||||
*
|
||||
* This file includes the referenced bin path (../phpunit/phpunit/phpunit)
|
||||
* using a stream wrapper to prevent the shebang from being output on PHP<8
|
||||
*
|
||||
* @generated
|
||||
*/
|
||||
|
||||
namespace Composer;
|
||||
|
||||
$GLOBALS['_composer_bin_dir'] = __DIR__;
|
||||
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
|
||||
$GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST'] = $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'] = array(realpath(__DIR__ . '/..'.'/phpunit/phpunit/phpunit'));
|
||||
|
||||
if (PHP_VERSION_ID < 80000) {
|
||||
if (!class_exists('Composer\BinProxyWrapper')) {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class BinProxyWrapper
|
||||
{
|
||||
private $handle;
|
||||
private $position;
|
||||
private $realpath;
|
||||
|
||||
public function stream_open($path, $mode, $options, &$opened_path)
|
||||
{
|
||||
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
|
||||
$opened_path = substr($path, 17);
|
||||
$this->realpath = realpath($opened_path) ?: $opened_path;
|
||||
$opened_path = 'phpvfscomposer://'.$this->realpath;
|
||||
$this->handle = fopen($this->realpath, $mode);
|
||||
$this->position = 0;
|
||||
|
||||
return (bool) $this->handle;
|
||||
}
|
||||
|
||||
public function stream_read($count)
|
||||
{
|
||||
$data = fread($this->handle, $count);
|
||||
|
||||
if ($this->position === 0) {
|
||||
$data = preg_replace('{^#!.*\r?\n}', '', $data);
|
||||
}
|
||||
$data = str_replace('__DIR__', var_export(dirname($this->realpath), true), $data);
|
||||
$data = str_replace('__FILE__', var_export($this->realpath, true), $data);
|
||||
|
||||
$this->position += strlen($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function stream_cast($castAs)
|
||||
{
|
||||
return $this->handle;
|
||||
}
|
||||
|
||||
public function stream_close()
|
||||
{
|
||||
fclose($this->handle);
|
||||
}
|
||||
|
||||
public function stream_lock($operation)
|
||||
{
|
||||
return $operation ? flock($this->handle, $operation) : true;
|
||||
}
|
||||
|
||||
public function stream_seek($offset, $whence)
|
||||
{
|
||||
if (0 === fseek($this->handle, $offset, $whence)) {
|
||||
$this->position = ftell($this->handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function stream_tell()
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function stream_eof()
|
||||
{
|
||||
return feof($this->handle);
|
||||
}
|
||||
|
||||
public function stream_stat()
|
||||
{
|
||||
return array();
|
||||
}
|
||||
|
||||
public function stream_set_option($option, $arg1, $arg2)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function url_stat($path, $flags)
|
||||
{
|
||||
$path = substr($path, 17);
|
||||
if (file_exists($path)) {
|
||||
return stat($path);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
(function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
|
||||
|| (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
|
||||
) {
|
||||
return include("phpvfscomposer://" . __DIR__ . '/..'.'/phpunit/phpunit/phpunit');
|
||||
}
|
||||
}
|
||||
|
||||
return include __DIR__ . '/..'.'/phpunit/phpunit/phpunit';
|
5
vendor/bin/phpunit.bat
vendored
5
vendor/bin/phpunit.bat
vendored
@@ -1,5 +0,0 @@
|
||||
@ECHO OFF
|
||||
setlocal DISABLEDELAYEDEXPANSION
|
||||
SET BIN_TARGET=%~dp0/phpunit
|
||||
SET COMPOSER_RUNTIME_BIN_DIR=%~dp0
|
||||
php "%BIN_TARGET%" %*
|
579
vendor/composer/ClassLoader.php
vendored
579
vendor/composer/ClassLoader.php
vendored
@@ -1,579 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Composer.
|
||||
*
|
||||
* (c) Nils Adermann <naderman@naderman.de>
|
||||
* Jordi Boggiano <j.boggiano@seld.be>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Composer\Autoload;
|
||||
|
||||
/**
|
||||
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
|
||||
*
|
||||
* $loader = new \Composer\Autoload\ClassLoader();
|
||||
*
|
||||
* // register classes with namespaces
|
||||
* $loader->add('Symfony\Component', __DIR__.'/component');
|
||||
* $loader->add('Symfony', __DIR__.'/framework');
|
||||
*
|
||||
* // activate the autoloader
|
||||
* $loader->register();
|
||||
*
|
||||
* // to enable searching the include path (eg. for PEAR packages)
|
||||
* $loader->setUseIncludePath(true);
|
||||
*
|
||||
* In this example, if you try to use a class in the Symfony\Component
|
||||
* namespace or one of its children (Symfony\Component\Console for instance),
|
||||
* the autoloader will first look for the class under the component/
|
||||
* directory, and it will then fallback to the framework/ directory if not
|
||||
* found before giving up.
|
||||
*
|
||||
* This class is loosely based on the Symfony UniversalClassLoader.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
* @author Jordi Boggiano <j.boggiano@seld.be>
|
||||
* @see https://www.php-fig.org/psr/psr-0/
|
||||
* @see https://www.php-fig.org/psr/psr-4/
|
||||
*/
|
||||
class ClassLoader
|
||||
{
|
||||
/** @var \Closure(string):void */
|
||||
private static $includeFile;
|
||||
|
||||
/** @var string|null */
|
||||
private $vendorDir;
|
||||
|
||||
// PSR-4
|
||||
/**
|
||||
* @var array<string, array<string, int>>
|
||||
*/
|
||||
private $prefixLengthsPsr4 = array();
|
||||
/**
|
||||
* @var array<string, list<string>>
|
||||
*/
|
||||
private $prefixDirsPsr4 = array();
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private $fallbackDirsPsr4 = array();
|
||||
|
||||
// PSR-0
|
||||
/**
|
||||
* List of PSR-0 prefixes
|
||||
*
|
||||
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
|
||||
*
|
||||
* @var array<string, array<string, list<string>>>
|
||||
*/
|
||||
private $prefixesPsr0 = array();
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private $fallbackDirsPsr0 = array();
|
||||
|
||||
/** @var bool */
|
||||
private $useIncludePath = false;
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private $classMap = array();
|
||||
|
||||
/** @var bool */
|
||||
private $classMapAuthoritative = false;
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private $missingClasses = array();
|
||||
|
||||
/** @var string|null */
|
||||
private $apcuPrefix;
|
||||
|
||||
/**
|
||||
* @var array<string, self>
|
||||
*/
|
||||
private static $registeredLoaders = array();
|
||||
|
||||
/**
|
||||
* @param string|null $vendorDir
|
||||
*/
|
||||
public function __construct($vendorDir = null)
|
||||
{
|
||||
$this->vendorDir = $vendorDir;
|
||||
self::initializeIncludeClosure();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function getPrefixes()
|
||||
{
|
||||
if (!empty($this->prefixesPsr0)) {
|
||||
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function getPrefixesPsr4()
|
||||
{
|
||||
return $this->prefixDirsPsr4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getFallbackDirs()
|
||||
{
|
||||
return $this->fallbackDirsPsr0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getFallbackDirsPsr4()
|
||||
{
|
||||
return $this->fallbackDirsPsr4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Array of classname => path
|
||||
*/
|
||||
public function getClassMap()
|
||||
{
|
||||
return $this->classMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $classMap Class to filename map
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addClassMap(array $classMap)
|
||||
{
|
||||
if ($this->classMap) {
|
||||
$this->classMap = array_merge($this->classMap, $classMap);
|
||||
} else {
|
||||
$this->classMap = $classMap;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-0 directories for a given prefix, either
|
||||
* appending or prepending to the ones previously set for this prefix.
|
||||
*
|
||||
* @param string $prefix The prefix
|
||||
* @param list<string>|string $paths The PSR-0 root directories
|
||||
* @param bool $prepend Whether to prepend the directories
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add($prefix, $paths, $prepend = false)
|
||||
{
|
||||
$paths = (array) $paths;
|
||||
if (!$prefix) {
|
||||
if ($prepend) {
|
||||
$this->fallbackDirsPsr0 = array_merge(
|
||||
$paths,
|
||||
$this->fallbackDirsPsr0
|
||||
);
|
||||
} else {
|
||||
$this->fallbackDirsPsr0 = array_merge(
|
||||
$this->fallbackDirsPsr0,
|
||||
$paths
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$first = $prefix[0];
|
||||
if (!isset($this->prefixesPsr0[$first][$prefix])) {
|
||||
$this->prefixesPsr0[$first][$prefix] = $paths;
|
||||
|
||||
return;
|
||||
}
|
||||
if ($prepend) {
|
||||
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||
$paths,
|
||||
$this->prefixesPsr0[$first][$prefix]
|
||||
);
|
||||
} else {
|
||||
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||
$this->prefixesPsr0[$first][$prefix],
|
||||
$paths
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-4 directories for a given namespace, either
|
||||
* appending or prepending to the ones previously set for this namespace.
|
||||
*
|
||||
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||
* @param list<string>|string $paths The PSR-4 base directories
|
||||
* @param bool $prepend Whether to prepend the directories
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addPsr4($prefix, $paths, $prepend = false)
|
||||
{
|
||||
$paths = (array) $paths;
|
||||
if (!$prefix) {
|
||||
// Register directories for the root namespace.
|
||||
if ($prepend) {
|
||||
$this->fallbackDirsPsr4 = array_merge(
|
||||
$paths,
|
||||
$this->fallbackDirsPsr4
|
||||
);
|
||||
} else {
|
||||
$this->fallbackDirsPsr4 = array_merge(
|
||||
$this->fallbackDirsPsr4,
|
||||
$paths
|
||||
);
|
||||
}
|
||||
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
|
||||
// Register directories for a new namespace.
|
||||
$length = strlen($prefix);
|
||||
if ('\\' !== $prefix[$length - 1]) {
|
||||
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||
}
|
||||
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||
$this->prefixDirsPsr4[$prefix] = $paths;
|
||||
} elseif ($prepend) {
|
||||
// Prepend directories for an already registered namespace.
|
||||
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||
$paths,
|
||||
$this->prefixDirsPsr4[$prefix]
|
||||
);
|
||||
} else {
|
||||
// Append directories for an already registered namespace.
|
||||
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||
$this->prefixDirsPsr4[$prefix],
|
||||
$paths
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-0 directories for a given prefix,
|
||||
* replacing any others previously set for this prefix.
|
||||
*
|
||||
* @param string $prefix The prefix
|
||||
* @param list<string>|string $paths The PSR-0 base directories
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set($prefix, $paths)
|
||||
{
|
||||
if (!$prefix) {
|
||||
$this->fallbackDirsPsr0 = (array) $paths;
|
||||
} else {
|
||||
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-4 directories for a given namespace,
|
||||
* replacing any others previously set for this namespace.
|
||||
*
|
||||
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||
* @param list<string>|string $paths The PSR-4 base directories
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setPsr4($prefix, $paths)
|
||||
{
|
||||
if (!$prefix) {
|
||||
$this->fallbackDirsPsr4 = (array) $paths;
|
||||
} else {
|
||||
$length = strlen($prefix);
|
||||
if ('\\' !== $prefix[$length - 1]) {
|
||||
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||
}
|
||||
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||
$this->prefixDirsPsr4[$prefix] = (array) $paths;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns on searching the include path for class files.
|
||||
*
|
||||
* @param bool $useIncludePath
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setUseIncludePath($useIncludePath)
|
||||
{
|
||||
$this->useIncludePath = $useIncludePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to check if the autoloader uses the include path to check
|
||||
* for classes.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getUseIncludePath()
|
||||
{
|
||||
return $this->useIncludePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns off searching the prefix and fallback directories for classes
|
||||
* that have not been registered with the class map.
|
||||
*
|
||||
* @param bool $classMapAuthoritative
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setClassMapAuthoritative($classMapAuthoritative)
|
||||
{
|
||||
$this->classMapAuthoritative = $classMapAuthoritative;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should class lookup fail if not found in the current class map?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isClassMapAuthoritative()
|
||||
{
|
||||
return $this->classMapAuthoritative;
|
||||
}
|
||||
|
||||
/**
|
||||
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
|
||||
*
|
||||
* @param string|null $apcuPrefix
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setApcuPrefix($apcuPrefix)
|
||||
{
|
||||
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The APCu prefix in use, or null if APCu caching is not enabled.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getApcuPrefix()
|
||||
{
|
||||
return $this->apcuPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers this instance as an autoloader.
|
||||
*
|
||||
* @param bool $prepend Whether to prepend the autoloader or not
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register($prepend = false)
|
||||
{
|
||||
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
|
||||
|
||||
if (null === $this->vendorDir) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($prepend) {
|
||||
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
|
||||
} else {
|
||||
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||
self::$registeredLoaders[$this->vendorDir] = $this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters this instance as an autoloader.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function unregister()
|
||||
{
|
||||
spl_autoload_unregister(array($this, 'loadClass'));
|
||||
|
||||
if (null !== $this->vendorDir) {
|
||||
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the given class or interface.
|
||||
*
|
||||
* @param string $class The name of the class
|
||||
* @return true|null True if loaded, null otherwise
|
||||
*/
|
||||
public function loadClass($class)
|
||||
{
|
||||
if ($file = $this->findFile($class)) {
|
||||
$includeFile = self::$includeFile;
|
||||
$includeFile($file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the path to the file where the class is defined.
|
||||
*
|
||||
* @param string $class The name of the class
|
||||
*
|
||||
* @return string|false The path if found, false otherwise
|
||||
*/
|
||||
public function findFile($class)
|
||||
{
|
||||
// class map lookup
|
||||
if (isset($this->classMap[$class])) {
|
||||
return $this->classMap[$class];
|
||||
}
|
||||
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
|
||||
return false;
|
||||
}
|
||||
if (null !== $this->apcuPrefix) {
|
||||
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
|
||||
if ($hit) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
$file = $this->findFileWithExtension($class, '.php');
|
||||
|
||||
// Search for Hack files if we are running on HHVM
|
||||
if (false === $file && defined('HHVM_VERSION')) {
|
||||
$file = $this->findFileWithExtension($class, '.hh');
|
||||
}
|
||||
|
||||
if (null !== $this->apcuPrefix) {
|
||||
apcu_add($this->apcuPrefix.$class, $file);
|
||||
}
|
||||
|
||||
if (false === $file) {
|
||||
// Remember that this class does not exist.
|
||||
$this->missingClasses[$class] = true;
|
||||
}
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently registered loaders keyed by their corresponding vendor directories.
|
||||
*
|
||||
* @return array<string, self>
|
||||
*/
|
||||
public static function getRegisteredLoaders()
|
||||
{
|
||||
return self::$registeredLoaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $class
|
||||
* @param string $ext
|
||||
* @return string|false
|
||||
*/
|
||||
private function findFileWithExtension($class, $ext)
|
||||
{
|
||||
// PSR-4 lookup
|
||||
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
|
||||
|
||||
$first = $class[0];
|
||||
if (isset($this->prefixLengthsPsr4[$first])) {
|
||||
$subPath = $class;
|
||||
while (false !== $lastPos = strrpos($subPath, '\\')) {
|
||||
$subPath = substr($subPath, 0, $lastPos);
|
||||
$search = $subPath . '\\';
|
||||
if (isset($this->prefixDirsPsr4[$search])) {
|
||||
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
|
||||
foreach ($this->prefixDirsPsr4[$search] as $dir) {
|
||||
if (file_exists($file = $dir . $pathEnd)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-4 fallback dirs
|
||||
foreach ($this->fallbackDirsPsr4 as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 lookup
|
||||
if (false !== $pos = strrpos($class, '\\')) {
|
||||
// namespaced class name
|
||||
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
|
||||
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
|
||||
} else {
|
||||
// PEAR-like class name
|
||||
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
|
||||
}
|
||||
|
||||
if (isset($this->prefixesPsr0[$first])) {
|
||||
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
|
||||
if (0 === strpos($class, $prefix)) {
|
||||
foreach ($dirs as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 fallback dirs
|
||||
foreach ($this->fallbackDirsPsr0 as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 include paths.
|
||||
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
private static function initializeIncludeClosure()
|
||||
{
|
||||
if (self::$includeFile !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope isolated include.
|
||||
*
|
||||
* Prevents access to $this/self from included files.
|
||||
*
|
||||
* @param string $file
|
||||
* @return void
|
||||
*/
|
||||
self::$includeFile = \Closure::bind(static function($file) {
|
||||
include $file;
|
||||
}, null, null);
|
||||
}
|
||||
}
|
378
vendor/composer/InstalledVersions.php
vendored
378
vendor/composer/InstalledVersions.php
vendored
@@ -1,378 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Composer.
|
||||
*
|
||||
* (c) Nils Adermann <naderman@naderman.de>
|
||||
* Jordi Boggiano <j.boggiano@seld.be>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Composer;
|
||||
|
||||
use Composer\Autoload\ClassLoader;
|
||||
use Composer\Semver\VersionParser;
|
||||
|
||||
/**
|
||||
* This class is copied in every Composer installed project and available to all
|
||||
*
|
||||
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
|
||||
*
|
||||
* To require its presence, you can require `composer-runtime-api ^2.0`
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class InstalledVersions
|
||||
{
|
||||
/**
|
||||
* @var mixed[]|null
|
||||
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
|
||||
*/
|
||||
private static $installed;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private static $installedIsLocalDir;
|
||||
|
||||
/**
|
||||
* @var bool|null
|
||||
*/
|
||||
private static $canGetVendors;
|
||||
|
||||
/**
|
||||
* @var array[]
|
||||
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
private static $installedByVendor = array();
|
||||
|
||||
/**
|
||||
* Returns a list of all package names which are present, either by being installed, replaced or provided
|
||||
*
|
||||
* @return string[]
|
||||
* @psalm-return list<string>
|
||||
*/
|
||||
public static function getInstalledPackages()
|
||||
{
|
||||
$packages = array();
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
$packages[] = array_keys($installed['versions']);
|
||||
}
|
||||
|
||||
if (1 === \count($packages)) {
|
||||
return $packages[0];
|
||||
}
|
||||
|
||||
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of all package names with a specific type e.g. 'library'
|
||||
*
|
||||
* @param string $type
|
||||
* @return string[]
|
||||
* @psalm-return list<string>
|
||||
*/
|
||||
public static function getInstalledPackagesByType($type)
|
||||
{
|
||||
$packagesByType = array();
|
||||
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
foreach ($installed['versions'] as $name => $package) {
|
||||
if (isset($package['type']) && $package['type'] === $type) {
|
||||
$packagesByType[] = $name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $packagesByType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given package is installed
|
||||
*
|
||||
* This also returns true if the package name is provided or replaced by another package
|
||||
*
|
||||
* @param string $packageName
|
||||
* @param bool $includeDevRequirements
|
||||
* @return bool
|
||||
*/
|
||||
public static function isInstalled($packageName, $includeDevRequirements = true)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (isset($installed['versions'][$packageName])) {
|
||||
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given package satisfies a version constraint
|
||||
*
|
||||
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
|
||||
*
|
||||
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
|
||||
*
|
||||
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
|
||||
* @param string $packageName
|
||||
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
|
||||
* @return bool
|
||||
*/
|
||||
public static function satisfies(VersionParser $parser, $packageName, $constraint)
|
||||
{
|
||||
$constraint = $parser->parseConstraints((string) $constraint);
|
||||
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
|
||||
|
||||
return $provided->matches($constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a version constraint representing all the range(s) which are installed for a given package
|
||||
*
|
||||
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
|
||||
* whether a given version of a package is installed, and not just whether it exists
|
||||
*
|
||||
* @param string $packageName
|
||||
* @return string Version constraint usable with composer/semver
|
||||
*/
|
||||
public static function getVersionRanges($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ranges = array();
|
||||
if (isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
|
||||
}
|
||||
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
|
||||
}
|
||||
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
|
||||
}
|
||||
if (array_key_exists('provided', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
|
||||
}
|
||||
|
||||
return implode(' || ', $ranges);
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||
*/
|
||||
public static function getVersion($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['version'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['version'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||
*/
|
||||
public static function getPrettyVersion($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['pretty_version'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
|
||||
*/
|
||||
public static function getReference($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['reference'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['reference'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
|
||||
*/
|
||||
public static function getInstallPath($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
|
||||
*/
|
||||
public static function getRootPackage()
|
||||
{
|
||||
$installed = self::getInstalled();
|
||||
|
||||
return $installed[0]['root'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw installed.php data for custom implementations
|
||||
*
|
||||
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
|
||||
* @return array[]
|
||||
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
|
||||
*/
|
||||
public static function getRawData()
|
||||
{
|
||||
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
|
||||
|
||||
if (null === self::$installed) {
|
||||
// only require the installed.php file if this file is loaded from its dumped location,
|
||||
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||
self::$installed = include __DIR__ . '/installed.php';
|
||||
} else {
|
||||
self::$installed = array();
|
||||
}
|
||||
}
|
||||
|
||||
return self::$installed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw data of all installed.php which are currently loaded for custom implementations
|
||||
*
|
||||
* @return array[]
|
||||
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
public static function getAllRawData()
|
||||
{
|
||||
return self::getInstalled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets you reload the static array from another file
|
||||
*
|
||||
* This is only useful for complex integrations in which a project needs to use
|
||||
* this class but then also needs to execute another project's autoloader in process,
|
||||
* and wants to ensure both projects have access to their version of installed.php.
|
||||
*
|
||||
* A typical case would be PHPUnit, where it would need to make sure it reads all
|
||||
* the data it needs from this class, then call reload() with
|
||||
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
|
||||
* the project in which it runs can then also use this class safely, without
|
||||
* interference between PHPUnit's dependencies and the project's dependencies.
|
||||
*
|
||||
* @param array[] $data A vendor/composer/installed.php data set
|
||||
* @return void
|
||||
*
|
||||
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
|
||||
*/
|
||||
public static function reload($data)
|
||||
{
|
||||
self::$installed = $data;
|
||||
self::$installedByVendor = array();
|
||||
|
||||
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
|
||||
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
|
||||
// so we have to assume it does not, and that may result in duplicate data being returned when listing
|
||||
// all installed packages for example
|
||||
self::$installedIsLocalDir = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array[]
|
||||
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
private static function getInstalled()
|
||||
{
|
||||
if (null === self::$canGetVendors) {
|
||||
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
|
||||
}
|
||||
|
||||
$installed = array();
|
||||
$copiedLocalDir = false;
|
||||
|
||||
if (self::$canGetVendors) {
|
||||
$selfDir = strtr(__DIR__, '\\', '/');
|
||||
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
|
||||
$vendorDir = strtr($vendorDir, '\\', '/');
|
||||
if (isset(self::$installedByVendor[$vendorDir])) {
|
||||
$installed[] = self::$installedByVendor[$vendorDir];
|
||||
} elseif (is_file($vendorDir.'/composer/installed.php')) {
|
||||
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||
$required = require $vendorDir.'/composer/installed.php';
|
||||
self::$installedByVendor[$vendorDir] = $required;
|
||||
$installed[] = $required;
|
||||
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
|
||||
self::$installed = $required;
|
||||
self::$installedIsLocalDir = true;
|
||||
}
|
||||
}
|
||||
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
|
||||
$copiedLocalDir = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (null === self::$installed) {
|
||||
// only require the installed.php file if this file is loaded from its dumped location,
|
||||
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||
$required = require __DIR__ . '/installed.php';
|
||||
self::$installed = $required;
|
||||
} else {
|
||||
self::$installed = array();
|
||||
}
|
||||
}
|
||||
|
||||
if (self::$installed !== array() && !$copiedLocalDir) {
|
||||
$installed[] = self::$installed;
|
||||
}
|
||||
|
||||
return $installed;
|
||||
}
|
||||
}
|
21
vendor/composer/LICENSE
vendored
21
vendor/composer/LICENSE
vendored
@@ -1,21 +0,0 @@
|
||||
|
||||
Copyright (c) Nils Adermann, Jordi Boggiano
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
1230
vendor/composer/autoload_classmap.php
vendored
1230
vendor/composer/autoload_classmap.php
vendored
File diff suppressed because it is too large
Load Diff
11
vendor/composer/autoload_files.php
vendored
11
vendor/composer/autoload_files.php
vendored
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
// autoload_files.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
|
||||
'ec07570ca5a812141189b1fa81503674' => $vendorDir . '/phpunit/phpunit/src/Framework/Assert/Functions.php',
|
||||
);
|
9
vendor/composer/autoload_namespaces.php
vendored
9
vendor/composer/autoload_namespaces.php
vendored
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
// autoload_namespaces.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
);
|
13
vendor/composer/autoload_psr4.php
vendored
13
vendor/composer/autoload_psr4.php
vendored
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
// autoload_psr4.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'goodboyalex\\php_components_pack\\tests\\' => array($baseDir . '/tests'),
|
||||
'goodboyalex\\php_components_pack\\' => array($baseDir . '/sources'),
|
||||
'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser'),
|
||||
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
|
||||
);
|
50
vendor/composer/autoload_real.php
vendored
50
vendor/composer/autoload_real.php
vendored
@@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
// autoload_real.php @generated by Composer
|
||||
|
||||
class ComposerAutoloaderInitc00e5b601adae61bbbc3f6be4864ef55
|
||||
{
|
||||
private static $loader;
|
||||
|
||||
public static function loadClassLoader($class)
|
||||
{
|
||||
if ('Composer\Autoload\ClassLoader' === $class) {
|
||||
require __DIR__ . '/ClassLoader.php';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Composer\Autoload\ClassLoader
|
||||
*/
|
||||
public static function getLoader()
|
||||
{
|
||||
if (null !== self::$loader) {
|
||||
return self::$loader;
|
||||
}
|
||||
|
||||
require __DIR__ . '/platform_check.php';
|
||||
|
||||
spl_autoload_register(array('ComposerAutoloaderInitc00e5b601adae61bbbc3f6be4864ef55', 'loadClassLoader'), true, true);
|
||||
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
|
||||
spl_autoload_unregister(array('ComposerAutoloaderInitc00e5b601adae61bbbc3f6be4864ef55', 'loadClassLoader'));
|
||||
|
||||
require __DIR__ . '/autoload_static.php';
|
||||
call_user_func(\Composer\Autoload\ComposerStaticInitc00e5b601adae61bbbc3f6be4864ef55::getInitializer($loader));
|
||||
|
||||
$loader->register(true);
|
||||
|
||||
$filesToLoad = \Composer\Autoload\ComposerStaticInitc00e5b601adae61bbbc3f6be4864ef55::$files;
|
||||
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
|
||||
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
|
||||
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
|
||||
|
||||
require $file;
|
||||
}
|
||||
}, null, null);
|
||||
foreach ($filesToLoad as $fileIdentifier => $file) {
|
||||
$requireFile($fileIdentifier, $file);
|
||||
}
|
||||
|
||||
return $loader;
|
||||
}
|
||||
}
|
1282
vendor/composer/autoload_static.php
vendored
1282
vendor/composer/autoload_static.php
vendored
File diff suppressed because it is too large
Load Diff
1803
vendor/composer/installed.json
vendored
1803
vendor/composer/installed.json
vendored
File diff suppressed because it is too large
Load Diff
266
vendor/composer/installed.php
vendored
266
vendor/composer/installed.php
vendored
@@ -1,266 +0,0 @@
|
||||
<?php return array(
|
||||
'root' => array(
|
||||
'name' => 'goodboyalex/php_components_pack',
|
||||
'pretty_version' => 'dev-master',
|
||||
'version' => 'dev-master',
|
||||
'reference' => '6ed1df2eda6978ae8b1fac707d7c0b762bfe491d',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'dev' => true,
|
||||
),
|
||||
'versions' => array(
|
||||
'goodboyalex/php_components_pack' => array(
|
||||
'pretty_version' => 'dev-master',
|
||||
'version' => 'dev-master',
|
||||
'reference' => '6ed1df2eda6978ae8b1fac707d7c0b762bfe491d',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'myclabs/deep-copy' => array(
|
||||
'pretty_version' => '1.12.1',
|
||||
'version' => '1.12.1.0',
|
||||
'reference' => '123267b2c49fbf30d78a7b2d333f6be754b94845',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../myclabs/deep-copy',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'nikic/php-parser' => array(
|
||||
'pretty_version' => 'v5.4.0',
|
||||
'version' => '5.4.0.0',
|
||||
'reference' => '447a020a1f875a434d62f2a401f53b82a396e494',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../nikic/php-parser',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phar-io/manifest' => array(
|
||||
'pretty_version' => '2.0.4',
|
||||
'version' => '2.0.4.0',
|
||||
'reference' => '54750ef60c58e43759730615a392c31c80e23176',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phar-io/manifest',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phar-io/version' => array(
|
||||
'pretty_version' => '3.2.1',
|
||||
'version' => '3.2.1.0',
|
||||
'reference' => '4f7fd7836c6f332bb2933569e566a0d6c4cbed74',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phar-io/version',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/php-code-coverage' => array(
|
||||
'pretty_version' => '11.0.8',
|
||||
'version' => '11.0.8.0',
|
||||
'reference' => '418c59fd080954f8c4aa5631d9502ecda2387118',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/php-code-coverage',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/php-file-iterator' => array(
|
||||
'pretty_version' => '5.1.0',
|
||||
'version' => '5.1.0.0',
|
||||
'reference' => '118cfaaa8bc5aef3287bf315b6060b1174754af6',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/php-file-iterator',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/php-invoker' => array(
|
||||
'pretty_version' => '5.0.1',
|
||||
'version' => '5.0.1.0',
|
||||
'reference' => 'c1ca3814734c07492b3d4c5f794f4b0995333da2',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/php-invoker',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/php-text-template' => array(
|
||||
'pretty_version' => '4.0.1',
|
||||
'version' => '4.0.1.0',
|
||||
'reference' => '3e0404dc6b300e6bf56415467ebcb3fe4f33e964',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/php-text-template',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/php-timer' => array(
|
||||
'pretty_version' => '7.0.1',
|
||||
'version' => '7.0.1.0',
|
||||
'reference' => '3b415def83fbcb41f991d9ebf16ae4ad8b7837b3',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/php-timer',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'phpunit/phpunit' => array(
|
||||
'pretty_version' => '11.5.6',
|
||||
'version' => '11.5.6.0',
|
||||
'reference' => '3c3ae14c90f244cdda95028c3e469028e8d1c02c',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpunit/phpunit',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/cli-parser' => array(
|
||||
'pretty_version' => '3.0.2',
|
||||
'version' => '3.0.2.0',
|
||||
'reference' => '15c5dd40dc4f38794d383bb95465193f5e0ae180',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/cli-parser',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/code-unit' => array(
|
||||
'pretty_version' => '3.0.2',
|
||||
'version' => '3.0.2.0',
|
||||
'reference' => 'ee88b0cdbe74cf8dd3b54940ff17643c0d6543ca',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/code-unit',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/code-unit-reverse-lookup' => array(
|
||||
'pretty_version' => '4.0.1',
|
||||
'version' => '4.0.1.0',
|
||||
'reference' => '183a9b2632194febd219bb9246eee421dad8d45e',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/code-unit-reverse-lookup',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/comparator' => array(
|
||||
'pretty_version' => '6.3.0',
|
||||
'version' => '6.3.0.0',
|
||||
'reference' => 'd4e47a769525c4dd38cea90e5dcd435ddbbc7115',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/comparator',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/complexity' => array(
|
||||
'pretty_version' => '4.0.1',
|
||||
'version' => '4.0.1.0',
|
||||
'reference' => 'ee41d384ab1906c68852636b6de493846e13e5a0',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/complexity',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/diff' => array(
|
||||
'pretty_version' => '6.0.2',
|
||||
'version' => '6.0.2.0',
|
||||
'reference' => 'b4ccd857127db5d41a5b676f24b51371d76d8544',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/diff',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/environment' => array(
|
||||
'pretty_version' => '7.2.0',
|
||||
'version' => '7.2.0.0',
|
||||
'reference' => '855f3ae0ab316bbafe1ba4e16e9f3c078d24a0c5',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/environment',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/exporter' => array(
|
||||
'pretty_version' => '6.3.0',
|
||||
'version' => '6.3.0.0',
|
||||
'reference' => '3473f61172093b2da7de1fb5782e1f24cc036dc3',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/exporter',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/global-state' => array(
|
||||
'pretty_version' => '7.0.2',
|
||||
'version' => '7.0.2.0',
|
||||
'reference' => '3be331570a721f9a4b5917f4209773de17f747d7',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/global-state',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/lines-of-code' => array(
|
||||
'pretty_version' => '3.0.1',
|
||||
'version' => '3.0.1.0',
|
||||
'reference' => 'd36ad0d782e5756913e42ad87cb2890f4ffe467a',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/lines-of-code',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/object-enumerator' => array(
|
||||
'pretty_version' => '6.0.1',
|
||||
'version' => '6.0.1.0',
|
||||
'reference' => 'f5b498e631a74204185071eb41f33f38d64608aa',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/object-enumerator',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/object-reflector' => array(
|
||||
'pretty_version' => '4.0.1',
|
||||
'version' => '4.0.1.0',
|
||||
'reference' => '6e1a43b411b2ad34146dee7524cb13a068bb35f9',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/object-reflector',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/recursion-context' => array(
|
||||
'pretty_version' => '6.0.2',
|
||||
'version' => '6.0.2.0',
|
||||
'reference' => '694d156164372abbd149a4b85ccda2e4670c0e16',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/recursion-context',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/type' => array(
|
||||
'pretty_version' => '5.1.0',
|
||||
'version' => '5.1.0.0',
|
||||
'reference' => '461b9c5da241511a2a0e8f240814fb23ce5c0aac',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/type',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'sebastian/version' => array(
|
||||
'pretty_version' => '5.0.2',
|
||||
'version' => '5.0.2.0',
|
||||
'reference' => 'c687e3387b99f5b03b6caa64c74b63e2936ff874',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../sebastian/version',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'staabm/side-effects-detector' => array(
|
||||
'pretty_version' => '1.0.5',
|
||||
'version' => '1.0.5.0',
|
||||
'reference' => 'd8334211a140ce329c13726d4a715adbddd0a163',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../staabm/side-effects-detector',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
'theseer/tokenizer' => array(
|
||||
'pretty_version' => '1.2.3',
|
||||
'version' => '1.2.3.0',
|
||||
'reference' => '737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../theseer/tokenizer',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => true,
|
||||
),
|
||||
),
|
||||
);
|
26
vendor/composer/platform_check.php
vendored
26
vendor/composer/platform_check.php
vendored
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
// platform_check.php @generated by Composer
|
||||
|
||||
$issues = array();
|
||||
|
||||
if (!(PHP_VERSION_ID >= 80400)) {
|
||||
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.4.0". You are running ' . PHP_VERSION . '.';
|
||||
}
|
||||
|
||||
if ($issues) {
|
||||
if (!headers_sent()) {
|
||||
header('HTTP/1.1 500 Internal Server Error');
|
||||
}
|
||||
if (!ini_get('display_errors')) {
|
||||
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
|
||||
} elseif (!headers_sent()) {
|
||||
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
|
||||
}
|
||||
}
|
||||
trigger_error(
|
||||
'Composer detected issues in your platform: ' . implode(' ', $issues),
|
||||
E_USER_ERROR
|
||||
);
|
||||
}
|
20
vendor/myclabs/deep-copy/LICENSE
vendored
20
vendor/myclabs/deep-copy/LICENSE
vendored
@@ -1,20 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 My C-Sense
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
406
vendor/myclabs/deep-copy/README.md
vendored
406
vendor/myclabs/deep-copy/README.md
vendored
@@ -1,406 +0,0 @@
|
||||
# DeepCopy
|
||||
|
||||
DeepCopy helps you create deep copies (clones) of your objects. It is designed to handle cycles in the association graph.
|
||||
|
||||
[](https://packagist.org/packages/myclabs/deep-copy)
|
||||
[](https://github.com/myclabs/DeepCopy/actions/workflows/ci.yaml)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [How](#how)
|
||||
1. [Why](#why)
|
||||
1. [Using simply `clone`](#using-simply-clone)
|
||||
1. [Overriding `__clone()`](#overriding-__clone)
|
||||
1. [With `DeepCopy`](#with-deepcopy)
|
||||
1. [How it works](#how-it-works)
|
||||
1. [Going further](#going-further)
|
||||
1. [Matchers](#matchers)
|
||||
1. [Property name](#property-name)
|
||||
1. [Specific property](#specific-property)
|
||||
1. [Type](#type)
|
||||
1. [Filters](#filters)
|
||||
1. [`SetNullFilter`](#setnullfilter-filter)
|
||||
1. [`KeepFilter`](#keepfilter-filter)
|
||||
1. [`DoctrineCollectionFilter`](#doctrinecollectionfilter-filter)
|
||||
1. [`DoctrineEmptyCollectionFilter`](#doctrineemptycollectionfilter-filter)
|
||||
1. [`DoctrineProxyFilter`](#doctrineproxyfilter-filter)
|
||||
1. [`ReplaceFilter`](#replacefilter-type-filter)
|
||||
1. [`ShallowCopyFilter`](#shallowcopyfilter-type-filter)
|
||||
1. [Edge cases](#edge-cases)
|
||||
1. [Contributing](#contributing)
|
||||
1. [Tests](#tests)
|
||||
|
||||
|
||||
## How?
|
||||
|
||||
Install with Composer:
|
||||
|
||||
```
|
||||
composer require myclabs/deep-copy
|
||||
```
|
||||
|
||||
Use it:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$myCopy = $copier->copy($myObject);
|
||||
```
|
||||
|
||||
|
||||
## Why?
|
||||
|
||||
- How do you create copies of your objects?
|
||||
|
||||
```php
|
||||
$myCopy = clone $myObject;
|
||||
```
|
||||
|
||||
- How do you create **deep** copies of your objects (i.e. copying also all the objects referenced in the properties)?
|
||||
|
||||
You use [`__clone()`](http://www.php.net/manual/en/language.oop5.cloning.php#object.clone) and implement the behavior
|
||||
yourself.
|
||||
|
||||
- But how do you handle **cycles** in the association graph?
|
||||
|
||||
Now you're in for a big mess :(
|
||||
|
||||

|
||||
|
||||
|
||||
### Using simply `clone`
|
||||
|
||||

|
||||
|
||||
|
||||
### Overriding `__clone()`
|
||||
|
||||

|
||||
|
||||
|
||||
### With `DeepCopy`
|
||||
|
||||

|
||||
|
||||
|
||||
## How it works
|
||||
|
||||
DeepCopy recursively traverses all the object's properties and clones them. To avoid cloning the same object twice it
|
||||
keeps a hash map of all instances and thus preserves the object graph.
|
||||
|
||||
To use it:
|
||||
|
||||
```php
|
||||
use function DeepCopy\deep_copy;
|
||||
|
||||
$copy = deep_copy($var);
|
||||
```
|
||||
|
||||
Alternatively, you can create your own `DeepCopy` instance to configure it differently for example:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
|
||||
$copier = new DeepCopy(true);
|
||||
|
||||
$copy = $copier->copy($var);
|
||||
```
|
||||
|
||||
You may want to roll your own deep copy function:
|
||||
|
||||
```php
|
||||
namespace Acme;
|
||||
|
||||
use DeepCopy\DeepCopy;
|
||||
|
||||
function deep_copy($var)
|
||||
{
|
||||
static $copier = null;
|
||||
|
||||
if (null === $copier) {
|
||||
$copier = new DeepCopy(true);
|
||||
}
|
||||
|
||||
return $copier->copy($var);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Going further
|
||||
|
||||
You can add filters to customize the copy process.
|
||||
|
||||
The method to add a filter is `DeepCopy\DeepCopy::addFilter($filter, $matcher)`,
|
||||
with `$filter` implementing `DeepCopy\Filter\Filter`
|
||||
and `$matcher` implementing `DeepCopy\Matcher\Matcher`.
|
||||
|
||||
We provide some generic filters and matchers.
|
||||
|
||||
|
||||
### Matchers
|
||||
|
||||
- `DeepCopy\Matcher` applies on a object attribute.
|
||||
- `DeepCopy\TypeMatcher` applies on any element found in graph, including array elements.
|
||||
|
||||
|
||||
#### Property name
|
||||
|
||||
The `PropertyNameMatcher` will match a property by its name:
|
||||
|
||||
```php
|
||||
use DeepCopy\Matcher\PropertyNameMatcher;
|
||||
|
||||
// Will apply a filter to any property of any objects named "id"
|
||||
$matcher = new PropertyNameMatcher('id');
|
||||
```
|
||||
|
||||
|
||||
#### Specific property
|
||||
|
||||
The `PropertyMatcher` will match a specific property of a specific class:
|
||||
|
||||
```php
|
||||
use DeepCopy\Matcher\PropertyMatcher;
|
||||
|
||||
// Will apply a filter to the property "id" of any objects of the class "MyClass"
|
||||
$matcher = new PropertyMatcher('MyClass', 'id');
|
||||
```
|
||||
|
||||
|
||||
#### Type
|
||||
|
||||
The `TypeMatcher` will match any element by its type (instance of a class or any value that could be parameter of
|
||||
[gettype()](http://php.net/manual/en/function.gettype.php) function):
|
||||
|
||||
```php
|
||||
use DeepCopy\TypeMatcher\TypeMatcher;
|
||||
|
||||
// Will apply a filter to any object that is an instance of Doctrine\Common\Collections\Collection
|
||||
$matcher = new TypeMatcher('Doctrine\Common\Collections\Collection');
|
||||
```
|
||||
|
||||
|
||||
### Filters
|
||||
|
||||
- `DeepCopy\Filter` applies a transformation to the object attribute matched by `DeepCopy\Matcher`
|
||||
- `DeepCopy\TypeFilter` applies a transformation to any element matched by `DeepCopy\TypeMatcher`
|
||||
|
||||
By design, matching a filter will stop the chain of filters (i.e. the next ones will not be applied).
|
||||
Using the ([`ChainableFilter`](#chainablefilter-filter)) won't stop the chain of filters.
|
||||
|
||||
|
||||
#### `SetNullFilter` (filter)
|
||||
|
||||
Let's say for example that you are copying a database record (or a Doctrine entity), so you want the copy not to have
|
||||
any ID:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\SetNullFilter;
|
||||
use DeepCopy\Matcher\PropertyNameMatcher;
|
||||
|
||||
$object = MyClass::load(123);
|
||||
echo $object->id; // 123
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
|
||||
echo $copy->id; // null
|
||||
```
|
||||
|
||||
|
||||
#### `KeepFilter` (filter)
|
||||
|
||||
If you want a property to remain untouched (for example, an association to an object):
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\KeepFilter;
|
||||
use DeepCopy\Matcher\PropertyMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new KeepFilter(), new PropertyMatcher('MyClass', 'category'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
// $copy->category has not been touched
|
||||
```
|
||||
|
||||
|
||||
#### `ChainableFilter` (filter)
|
||||
|
||||
If you use cloning on proxy classes, you might want to apply two filters for:
|
||||
1. loading the data
|
||||
2. applying a transformation
|
||||
|
||||
You can use the `ChainableFilter` as a decorator of the proxy loader filter, which won't stop the chain of filters (i.e.
|
||||
the next ones may be applied).
|
||||
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\ChainableFilter;
|
||||
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
|
||||
use DeepCopy\Filter\SetNullFilter;
|
||||
use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher;
|
||||
use DeepCopy\Matcher\PropertyNameMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new ChainableFilter(new DoctrineProxyFilter()), new DoctrineProxyMatcher());
|
||||
$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
|
||||
echo $copy->id; // null
|
||||
```
|
||||
|
||||
|
||||
#### `DoctrineCollectionFilter` (filter)
|
||||
|
||||
If you use Doctrine and want to copy an entity, you will need to use the `DoctrineCollectionFilter`:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\Doctrine\DoctrineCollectionFilter;
|
||||
use DeepCopy\Matcher\PropertyTypeMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new DoctrineCollectionFilter(), new PropertyTypeMatcher('Doctrine\Common\Collections\Collection'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
```
|
||||
|
||||
|
||||
#### `DoctrineEmptyCollectionFilter` (filter)
|
||||
|
||||
If you use Doctrine and want to copy an entity who contains a `Collection` that you want to be reset, you can use the
|
||||
`DoctrineEmptyCollectionFilter`
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\Doctrine\DoctrineEmptyCollectionFilter;
|
||||
use DeepCopy\Matcher\PropertyMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new DoctrineEmptyCollectionFilter(), new PropertyMatcher('MyClass', 'myProperty'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
|
||||
// $copy->myProperty will return an empty collection
|
||||
```
|
||||
|
||||
|
||||
#### `DoctrineProxyFilter` (filter)
|
||||
|
||||
If you use Doctrine and use cloning on lazy loaded entities, you might encounter errors mentioning missing fields on a
|
||||
Doctrine proxy class (...\\\_\_CG\_\_\Proxy).
|
||||
You can use the `DoctrineProxyFilter` to load the actual entity behind the Doctrine proxy class.
|
||||
**Make sure, though, to put this as one of your very first filters in the filter chain so that the entity is loaded
|
||||
before other filters are applied!**
|
||||
We recommend to decorate the `DoctrineProxyFilter` with the `ChainableFilter` to allow applying other filters to the
|
||||
cloned lazy loaded entities.
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
|
||||
use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$copier->addFilter(new ChainableFilter(new DoctrineProxyFilter()), new DoctrineProxyMatcher());
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
|
||||
// $copy should now contain a clone of all entities, including those that were not yet fully loaded.
|
||||
```
|
||||
|
||||
|
||||
#### `ReplaceFilter` (type filter)
|
||||
|
||||
1. If you want to replace the value of a property:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\Filter\ReplaceFilter;
|
||||
use DeepCopy\Matcher\PropertyMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$callback = function ($currentValue) {
|
||||
return $currentValue . ' (copy)'
|
||||
};
|
||||
$copier->addFilter(new ReplaceFilter($callback), new PropertyMatcher('MyClass', 'title'));
|
||||
|
||||
$copy = $copier->copy($object);
|
||||
|
||||
// $copy->title will contain the data returned by the callback, e.g. 'The title (copy)'
|
||||
```
|
||||
|
||||
2. If you want to replace whole element:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\TypeFilter\ReplaceFilter;
|
||||
use DeepCopy\TypeMatcher\TypeMatcher;
|
||||
|
||||
$copier = new DeepCopy();
|
||||
$callback = function (MyClass $myClass) {
|
||||
return get_class($myClass);
|
||||
};
|
||||
$copier->addTypeFilter(new ReplaceFilter($callback), new TypeMatcher('MyClass'));
|
||||
|
||||
$copy = $copier->copy([new MyClass, 'some string', new MyClass]);
|
||||
|
||||
// $copy will contain ['MyClass', 'some string', 'MyClass']
|
||||
```
|
||||
|
||||
|
||||
The `$callback` parameter of the `ReplaceFilter` constructor accepts any PHP callable.
|
||||
|
||||
|
||||
#### `ShallowCopyFilter` (type filter)
|
||||
|
||||
Stop *DeepCopy* from recursively copying element, using standard `clone` instead:
|
||||
|
||||
```php
|
||||
use DeepCopy\DeepCopy;
|
||||
use DeepCopy\TypeFilter\ShallowCopyFilter;
|
||||
use DeepCopy\TypeMatcher\TypeMatcher;
|
||||
use Mockery as m;
|
||||
|
||||
$this->deepCopy = new DeepCopy();
|
||||
$this->deepCopy->addTypeFilter(
|
||||
new ShallowCopyFilter,
|
||||
new TypeMatcher(m\MockInterface::class)
|
||||
);
|
||||
|
||||
$myServiceWithMocks = new MyService(m::mock(MyDependency1::class), m::mock(MyDependency2::class));
|
||||
// All mocks will be just cloned, not deep copied
|
||||
```
|
||||
|
||||
|
||||
## Edge cases
|
||||
|
||||
The following structures cannot be deep-copied with PHP Reflection. As a result they are shallow cloned and filters are
|
||||
not applied. There is two ways for you to handle them:
|
||||
|
||||
- Implement your own `__clone()` method
|
||||
- Use a filter with a type matcher
|
||||
|
||||
|
||||
## Contributing
|
||||
|
||||
DeepCopy is distributed under the MIT license.
|
||||
|
||||
|
||||
### Tests
|
||||
|
||||
Running the tests is simple:
|
||||
|
||||
```php
|
||||
vendor/bin/phpunit
|
||||
```
|
||||
|
||||
### Support
|
||||
|
||||
Get professional support via [the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-myclabs-deep-copy?utm_source=packagist-myclabs-deep-copy&utm_medium=referral&utm_campaign=readme).
|
43
vendor/myclabs/deep-copy/composer.json
vendored
43
vendor/myclabs/deep-copy/composer.json
vendored
@@ -1,43 +0,0 @@
|
||||
{
|
||||
"name": "myclabs/deep-copy",
|
||||
"description": "Create deep copies (clones) of your objects",
|
||||
"license": "MIT",
|
||||
"type": "library",
|
||||
"keywords": [
|
||||
"clone",
|
||||
"copy",
|
||||
"duplicate",
|
||||
"object",
|
||||
"object graph"
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1 || ^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"doctrine/collections": "^1.6.8",
|
||||
"doctrine/common": "^2.13.3 || ^3.2.2",
|
||||
"phpspec/prophecy": "^1.10",
|
||||
"phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
|
||||
},
|
||||
"conflict": {
|
||||
"doctrine/collections": "<1.6.8",
|
||||
"doctrine/common": "<2.13.3 || >=3 <3.2.2"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"DeepCopy\\": "src/DeepCopy/"
|
||||
},
|
||||
"files": [
|
||||
"src/DeepCopy/deep_copy.php"
|
||||
]
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"DeepCopyTest\\": "tests/DeepCopyTest/",
|
||||
"DeepCopy\\": "fixtures/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
}
|
||||
}
|
316
vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php
vendored
316
vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php
vendored
@@ -1,316 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy;
|
||||
|
||||
use ArrayObject;
|
||||
use DateInterval;
|
||||
use DatePeriod;
|
||||
use DateTimeInterface;
|
||||
use DateTimeZone;
|
||||
use DeepCopy\Exception\CloneException;
|
||||
use DeepCopy\Filter\ChainableFilter;
|
||||
use DeepCopy\Filter\Filter;
|
||||
use DeepCopy\Matcher\Matcher;
|
||||
use DeepCopy\Reflection\ReflectionHelper;
|
||||
use DeepCopy\TypeFilter\Date\DateIntervalFilter;
|
||||
use DeepCopy\TypeFilter\Date\DatePeriodFilter;
|
||||
use DeepCopy\TypeFilter\Spl\ArrayObjectFilter;
|
||||
use DeepCopy\TypeFilter\Spl\SplDoublyLinkedListFilter;
|
||||
use DeepCopy\TypeFilter\TypeFilter;
|
||||
use DeepCopy\TypeMatcher\TypeMatcher;
|
||||
use ReflectionObject;
|
||||
use ReflectionProperty;
|
||||
use SplDoublyLinkedList;
|
||||
|
||||
/**
|
||||
* @final
|
||||
*/
|
||||
class DeepCopy
|
||||
{
|
||||
/**
|
||||
* @var object[] List of objects copied.
|
||||
*/
|
||||
private $hashMap = [];
|
||||
|
||||
/**
|
||||
* Filters to apply.
|
||||
*
|
||||
* @var array Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
|
||||
*/
|
||||
private $filters = [];
|
||||
|
||||
/**
|
||||
* Type Filters to apply.
|
||||
*
|
||||
* @var array Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
|
||||
*/
|
||||
private $typeFilters = [];
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $skipUncloneable = false;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $useCloneMethod;
|
||||
|
||||
/**
|
||||
* @param bool $useCloneMethod If set to true, when an object implements the __clone() function, it will be used
|
||||
* instead of the regular deep cloning.
|
||||
*/
|
||||
public function __construct($useCloneMethod = false)
|
||||
{
|
||||
$this->useCloneMethod = $useCloneMethod;
|
||||
|
||||
$this->addTypeFilter(new ArrayObjectFilter($this), new TypeMatcher(ArrayObject::class));
|
||||
$this->addTypeFilter(new DateIntervalFilter(), new TypeMatcher(DateInterval::class));
|
||||
$this->addTypeFilter(new DatePeriodFilter(), new TypeMatcher(DatePeriod::class));
|
||||
$this->addTypeFilter(new SplDoublyLinkedListFilter($this), new TypeMatcher(SplDoublyLinkedList::class));
|
||||
}
|
||||
|
||||
/**
|
||||
* If enabled, will not throw an exception when coming across an uncloneable property.
|
||||
*
|
||||
* @param $skipUncloneable
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function skipUncloneable($skipUncloneable = true)
|
||||
{
|
||||
$this->skipUncloneable = $skipUncloneable;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep copies the given object.
|
||||
*
|
||||
* @param mixed $object
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function copy($object)
|
||||
{
|
||||
$this->hashMap = [];
|
||||
|
||||
return $this->recursiveCopy($object);
|
||||
}
|
||||
|
||||
public function addFilter(Filter $filter, Matcher $matcher)
|
||||
{
|
||||
$this->filters[] = [
|
||||
'matcher' => $matcher,
|
||||
'filter' => $filter,
|
||||
];
|
||||
}
|
||||
|
||||
public function prependFilter(Filter $filter, Matcher $matcher)
|
||||
{
|
||||
array_unshift($this->filters, [
|
||||
'matcher' => $matcher,
|
||||
'filter' => $filter,
|
||||
]);
|
||||
}
|
||||
|
||||
public function addTypeFilter(TypeFilter $filter, TypeMatcher $matcher)
|
||||
{
|
||||
$this->typeFilters[] = [
|
||||
'matcher' => $matcher,
|
||||
'filter' => $filter,
|
||||
];
|
||||
}
|
||||
|
||||
private function recursiveCopy($var)
|
||||
{
|
||||
// Matches Type Filter
|
||||
if ($filter = $this->getFirstMatchedTypeFilter($this->typeFilters, $var)) {
|
||||
return $filter->apply($var);
|
||||
}
|
||||
|
||||
// Resource
|
||||
if (is_resource($var)) {
|
||||
return $var;
|
||||
}
|
||||
|
||||
// Array
|
||||
if (is_array($var)) {
|
||||
return $this->copyArray($var);
|
||||
}
|
||||
|
||||
// Scalar
|
||||
if (! is_object($var)) {
|
||||
return $var;
|
||||
}
|
||||
|
||||
// Enum
|
||||
if (PHP_VERSION_ID >= 80100 && enum_exists(get_class($var))) {
|
||||
return $var;
|
||||
}
|
||||
|
||||
// Object
|
||||
return $this->copyObject($var);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy an array
|
||||
* @param array $array
|
||||
* @return array
|
||||
*/
|
||||
private function copyArray(array $array)
|
||||
{
|
||||
foreach ($array as $key => $value) {
|
||||
$array[$key] = $this->recursiveCopy($value);
|
||||
}
|
||||
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies an object.
|
||||
*
|
||||
* @param object $object
|
||||
*
|
||||
* @throws CloneException
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
private function copyObject($object)
|
||||
{
|
||||
$objectHash = spl_object_hash($object);
|
||||
|
||||
if (isset($this->hashMap[$objectHash])) {
|
||||
return $this->hashMap[$objectHash];
|
||||
}
|
||||
|
||||
$reflectedObject = new ReflectionObject($object);
|
||||
$isCloneable = $reflectedObject->isCloneable();
|
||||
|
||||
if (false === $isCloneable) {
|
||||
if ($this->skipUncloneable) {
|
||||
$this->hashMap[$objectHash] = $object;
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
throw new CloneException(
|
||||
sprintf(
|
||||
'The class "%s" is not cloneable.',
|
||||
$reflectedObject->getName()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$newObject = clone $object;
|
||||
$this->hashMap[$objectHash] = $newObject;
|
||||
|
||||
if ($this->useCloneMethod && $reflectedObject->hasMethod('__clone')) {
|
||||
return $newObject;
|
||||
}
|
||||
|
||||
if ($newObject instanceof DateTimeInterface || $newObject instanceof DateTimeZone) {
|
||||
return $newObject;
|
||||
}
|
||||
|
||||
foreach (ReflectionHelper::getProperties($reflectedObject) as $property) {
|
||||
$this->copyObjectProperty($newObject, $property);
|
||||
}
|
||||
|
||||
return $newObject;
|
||||
}
|
||||
|
||||
private function copyObjectProperty($object, ReflectionProperty $property)
|
||||
{
|
||||
// Ignore static properties
|
||||
if ($property->isStatic()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore readonly properties
|
||||
if (method_exists($property, 'isReadOnly') && $property->isReadOnly()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply the filters
|
||||
foreach ($this->filters as $item) {
|
||||
/** @var Matcher $matcher */
|
||||
$matcher = $item['matcher'];
|
||||
/** @var Filter $filter */
|
||||
$filter = $item['filter'];
|
||||
|
||||
if ($matcher->matches($object, $property->getName())) {
|
||||
$filter->apply(
|
||||
$object,
|
||||
$property->getName(),
|
||||
function ($object) {
|
||||
return $this->recursiveCopy($object);
|
||||
}
|
||||
);
|
||||
|
||||
if ($filter instanceof ChainableFilter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If a filter matches, we stop processing this property
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$property->setAccessible(true);
|
||||
|
||||
// Ignore uninitialized properties (for PHP >7.4)
|
||||
if (method_exists($property, 'isInitialized') && !$property->isInitialized($object)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$propertyValue = $property->getValue($object);
|
||||
|
||||
// Copy the property
|
||||
$property->setValue($object, $this->recursiveCopy($propertyValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns first filter that matches variable, `null` if no such filter found.
|
||||
*
|
||||
* @param array $filterRecords Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and
|
||||
* 'matcher' with value of type {@see TypeMatcher}
|
||||
* @param mixed $var
|
||||
*
|
||||
* @return TypeFilter|null
|
||||
*/
|
||||
private function getFirstMatchedTypeFilter(array $filterRecords, $var)
|
||||
{
|
||||
$matched = $this->first(
|
||||
$filterRecords,
|
||||
function (array $record) use ($var) {
|
||||
/* @var TypeMatcher $matcher */
|
||||
$matcher = $record['matcher'];
|
||||
|
||||
return $matcher->matches($var);
|
||||
}
|
||||
);
|
||||
|
||||
return isset($matched) ? $matched['filter'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns first element that matches predicate, `null` if no such element found.
|
||||
*
|
||||
* @param array $elements Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
|
||||
* @param callable $predicate Predicate arguments are: element.
|
||||
*
|
||||
* @return array|null Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and 'matcher'
|
||||
* with value of type {@see TypeMatcher} or `null`.
|
||||
*/
|
||||
private function first(array $elements, callable $predicate)
|
||||
{
|
||||
foreach ($elements as $element) {
|
||||
if (call_user_func($predicate, $element)) {
|
||||
return $element;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Exception;
|
||||
|
||||
use UnexpectedValueException;
|
||||
|
||||
class CloneException extends UnexpectedValueException
|
||||
{
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Exception;
|
||||
|
||||
use ReflectionException;
|
||||
|
||||
class PropertyException extends ReflectionException
|
||||
{
|
||||
}
|
@@ -1,24 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter;
|
||||
|
||||
/**
|
||||
* Defines a decorator filter that will not stop the chain of filters.
|
||||
*/
|
||||
class ChainableFilter implements Filter
|
||||
{
|
||||
/**
|
||||
* @var Filter
|
||||
*/
|
||||
protected $filter;
|
||||
|
||||
public function __construct(Filter $filter)
|
||||
{
|
||||
$this->filter = $filter;
|
||||
}
|
||||
|
||||
public function apply($object, $property, $objectCopier)
|
||||
{
|
||||
$this->filter->apply($object, $property, $objectCopier);
|
||||
}
|
||||
}
|
@@ -1,33 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter\Doctrine;
|
||||
|
||||
use DeepCopy\Filter\Filter;
|
||||
use DeepCopy\Reflection\ReflectionHelper;
|
||||
|
||||
/**
|
||||
* @final
|
||||
*/
|
||||
class DoctrineCollectionFilter implements Filter
|
||||
{
|
||||
/**
|
||||
* Copies the object property doctrine collection.
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function apply($object, $property, $objectCopier)
|
||||
{
|
||||
$reflectionProperty = ReflectionHelper::getProperty($object, $property);
|
||||
|
||||
$reflectionProperty->setAccessible(true);
|
||||
$oldCollection = $reflectionProperty->getValue($object);
|
||||
|
||||
$newCollection = $oldCollection->map(
|
||||
function ($item) use ($objectCopier) {
|
||||
return $objectCopier($item);
|
||||
}
|
||||
);
|
||||
|
||||
$reflectionProperty->setValue($object, $newCollection);
|
||||
}
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter\Doctrine;
|
||||
|
||||
use DeepCopy\Filter\Filter;
|
||||
use DeepCopy\Reflection\ReflectionHelper;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* @final
|
||||
*/
|
||||
class DoctrineEmptyCollectionFilter implements Filter
|
||||
{
|
||||
/**
|
||||
* Sets the object property to an empty doctrine collection.
|
||||
*
|
||||
* @param object $object
|
||||
* @param string $property
|
||||
* @param callable $objectCopier
|
||||
*/
|
||||
public function apply($object, $property, $objectCopier)
|
||||
{
|
||||
$reflectionProperty = ReflectionHelper::getProperty($object, $property);
|
||||
$reflectionProperty->setAccessible(true);
|
||||
|
||||
$reflectionProperty->setValue($object, new ArrayCollection());
|
||||
}
|
||||
}
|
@@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter\Doctrine;
|
||||
|
||||
use DeepCopy\Filter\Filter;
|
||||
|
||||
/**
|
||||
* @final
|
||||
*/
|
||||
class DoctrineProxyFilter implements Filter
|
||||
{
|
||||
/**
|
||||
* Triggers the magic method __load() on a Doctrine Proxy class to load the
|
||||
* actual entity from the database.
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function apply($object, $property, $objectCopier)
|
||||
{
|
||||
$object->__load();
|
||||
}
|
||||
}
|
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter;
|
||||
|
||||
/**
|
||||
* Filter to apply to a property while copying an object
|
||||
*/
|
||||
interface Filter
|
||||
{
|
||||
/**
|
||||
* Applies the filter to the object.
|
||||
*
|
||||
* @param object $object
|
||||
* @param string $property
|
||||
* @param callable $objectCopier
|
||||
*/
|
||||
public function apply($object, $property, $objectCopier);
|
||||
}
|
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace DeepCopy\Filter;
|
||||
|
||||
class KeepFilter implements Filter
|
||||
{
|
||||
/**
|
||||
* Keeps the value of the object property.
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function apply($object, $property, $objectCopier)
|
||||
{
|
||||
// Nothing to do
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user