Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
# DeepCopy
2
 
3
DeepCopy helps you create deep copies (clones) of your objects. It is designed to handle cycles in the association graph.
4
 
5
[![Total Downloads](https://poser.pugx.org/myclabs/deep-copy/downloads.svg)](https://packagist.org/packages/myclabs/deep-copy)
6
[![Integrate](https://github.com/myclabs/DeepCopy/workflows/ci/badge.svg?branch=1.x)](https://github.com/myclabs/DeepCopy/actions)
7
 
8
## Table of Contents
9
 
10
1. [How](#how)
11
1. [Why](#why)
12
    1. [Using simply `clone`](#using-simply-clone)
13
    1. [Overriding `__clone()`](#overriding-__clone)
14
    1. [With `DeepCopy`](#with-deepcopy)
15
1. [How it works](#how-it-works)
16
1. [Going further](#going-further)
17
    1. [Matchers](#matchers)
18
        1. [Property name](#property-name)
19
        1. [Specific property](#specific-property)
20
        1. [Type](#type)
21
    1. [Filters](#filters)
22
        1. [`SetNullFilter`](#setnullfilter-filter)
23
        1. [`KeepFilter`](#keepfilter-filter)
24
        1. [`DoctrineCollectionFilter`](#doctrinecollectionfilter-filter)
25
        1. [`DoctrineEmptyCollectionFilter`](#doctrineemptycollectionfilter-filter)
26
        1. [`DoctrineProxyFilter`](#doctrineproxyfilter-filter)
27
        1. [`ReplaceFilter`](#replacefilter-type-filter)
28
        1. [`ShallowCopyFilter`](#shallowcopyfilter-type-filter)
29
1. [Edge cases](#edge-cases)
30
1. [Contributing](#contributing)
31
    1. [Tests](#tests)
32
 
33
 
34
## How?
35
 
36
Install with Composer:
37
 
38
```
39
composer require myclabs/deep-copy
40
```
41
 
42
Use it:
43
 
44
```php
45
use DeepCopy\DeepCopy;
46
 
47
$copier = new DeepCopy();
48
$myCopy = $copier->copy($myObject);
49
```
50
 
51
 
52
## Why?
53
 
54
- How do you create copies of your objects?
55
 
56
```php
57
$myCopy = clone $myObject;
58
```
59
 
60
- How do you create **deep** copies of your objects (i.e. copying also all the objects referenced in the properties)?
61
 
62
You use [`__clone()`](http://www.php.net/manual/en/language.oop5.cloning.php#object.clone) and implement the behavior
63
yourself.
64
 
65
- But how do you handle **cycles** in the association graph?
66
 
67
Now you're in for a big mess :(
68
 
69
![association graph](doc/graph.png)
70
 
71
 
72
### Using simply `clone`
73
 
74
![Using clone](doc/clone.png)
75
 
76
 
77
### Overriding `__clone()`
78
 
79
![Overriding __clone](doc/deep-clone.png)
80
 
81
 
82
### With `DeepCopy`
83
 
84
![With DeepCopy](doc/deep-copy.png)
85
 
86
 
87
## How it works
88
 
89
DeepCopy recursively traverses all the object's properties and clones them. To avoid cloning the same object twice it
90
keeps a hash map of all instances and thus preserves the object graph.
91
 
92
To use it:
93
 
94
```php
95
use function DeepCopy\deep_copy;
96
 
97
$copy = deep_copy($var);
98
```
99
 
100
Alternatively, you can create your own `DeepCopy` instance to configure it differently for example:
101
 
102
```php
103
use DeepCopy\DeepCopy;
104
 
105
$copier = new DeepCopy(true);
106
 
107
$copy = $copier->copy($var);
108
```
109
 
110
You may want to roll your own deep copy function:
111
 
112
```php
113
namespace Acme;
114
 
115
use DeepCopy\DeepCopy;
116
 
117
function deep_copy($var)
118
{
119
    static $copier = null;
120
 
121
    if (null === $copier) {
122
        $copier = new DeepCopy(true);
123
    }
124
 
125
    return $copier->copy($var);
126
}
127
```
128
 
129
 
130
## Going further
131
 
132
You can add filters to customize the copy process.
133
 
134
The method to add a filter is `DeepCopy\DeepCopy::addFilter($filter, $matcher)`,
135
with `$filter` implementing `DeepCopy\Filter\Filter`
136
and `$matcher` implementing `DeepCopy\Matcher\Matcher`.
137
 
138
We provide some generic filters and matchers.
139
 
140
 
141
### Matchers
142
 
143
  - `DeepCopy\Matcher` applies on a object attribute.
144
  - `DeepCopy\TypeMatcher` applies on any element found in graph, including array elements.
145
 
146
 
147
#### Property name
148
 
149
The `PropertyNameMatcher` will match a property by its name:
150
 
151
```php
152
use DeepCopy\Matcher\PropertyNameMatcher;
153
 
154
// Will apply a filter to any property of any objects named "id"
155
$matcher = new PropertyNameMatcher('id');
156
```
157
 
158
 
159
#### Specific property
160
 
161
The `PropertyMatcher` will match a specific property of a specific class:
162
 
163
```php
164
use DeepCopy\Matcher\PropertyMatcher;
165
 
166
// Will apply a filter to the property "id" of any objects of the class "MyClass"
167
$matcher = new PropertyMatcher('MyClass', 'id');
168
```
169
 
170
 
171
#### Type
172
 
173
The `TypeMatcher` will match any element by its type (instance of a class or any value that could be parameter of
174
[gettype()](http://php.net/manual/en/function.gettype.php) function):
175
 
176
```php
177
use DeepCopy\TypeMatcher\TypeMatcher;
178
 
179
// Will apply a filter to any object that is an instance of Doctrine\Common\Collections\Collection
180
$matcher = new TypeMatcher('Doctrine\Common\Collections\Collection');
181
```
182
 
183
 
184
### Filters
185
 
186
- `DeepCopy\Filter` applies a transformation to the object attribute matched by `DeepCopy\Matcher`
187
- `DeepCopy\TypeFilter` applies a transformation to any element matched by `DeepCopy\TypeMatcher`
188
 
991 lars 189
By design, matching a filter will stop the chain of filters (i.e. the next ones will not be applied).
190
Using the ([`ChainableFilter`](#chainablefilter-filter)) won't stop the chain of filters.
148 lars 191
 
991 lars 192
 
148 lars 193
#### `SetNullFilter` (filter)
194
 
195
Let's say for example that you are copying a database record (or a Doctrine entity), so you want the copy not to have
196
any ID:
197
 
198
```php
199
use DeepCopy\DeepCopy;
200
use DeepCopy\Filter\SetNullFilter;
201
use DeepCopy\Matcher\PropertyNameMatcher;
202
 
203
$object = MyClass::load(123);
204
echo $object->id; // 123
205
 
206
$copier = new DeepCopy();
207
$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id'));
208
 
209
$copy = $copier->copy($object);
210
 
211
echo $copy->id; // null
212
```
213
 
214
 
215
#### `KeepFilter` (filter)
216
 
217
If you want a property to remain untouched (for example, an association to an object):
218
 
219
```php
220
use DeepCopy\DeepCopy;
221
use DeepCopy\Filter\KeepFilter;
222
use DeepCopy\Matcher\PropertyMatcher;
223
 
224
$copier = new DeepCopy();
225
$copier->addFilter(new KeepFilter(), new PropertyMatcher('MyClass', 'category'));
226
 
227
$copy = $copier->copy($object);
228
// $copy->category has not been touched
229
```
230
 
231
 
991 lars 232
#### `ChainableFilter` (filter)
233
 
234
If you use cloning on proxy classes, you might want to apply two filters for:
235
1. loading the data
236
2. applying a transformation
237
 
238
You can use the `ChainableFilter` as a decorator of the proxy loader filter, which won't stop the chain of filters (i.e.
239
the next ones may be applied).
240
 
241
 
242
```php
243
use DeepCopy\DeepCopy;
244
use DeepCopy\Filter\ChainableFilter;
245
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
246
use DeepCopy\Filter\SetNullFilter;
247
use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher;
248
use DeepCopy\Matcher\PropertyNameMatcher;
249
 
250
$copier = new DeepCopy();
251
$copier->addFilter(new ChainableFilter(new DoctrineProxyFilter()), new DoctrineProxyMatcher());
252
$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id'));
253
 
254
$copy = $copier->copy($object);
255
 
256
echo $copy->id; // null
257
```
258
 
259
 
148 lars 260
#### `DoctrineCollectionFilter` (filter)
261
 
262
If you use Doctrine and want to copy an entity, you will need to use the `DoctrineCollectionFilter`:
263
 
264
```php
265
use DeepCopy\DeepCopy;
266
use DeepCopy\Filter\Doctrine\DoctrineCollectionFilter;
267
use DeepCopy\Matcher\PropertyTypeMatcher;
268
 
269
$copier = new DeepCopy();
270
$copier->addFilter(new DoctrineCollectionFilter(), new PropertyTypeMatcher('Doctrine\Common\Collections\Collection'));
271
 
272
$copy = $copier->copy($object);
273
```
274
 
275
 
276
#### `DoctrineEmptyCollectionFilter` (filter)
277
 
278
If you use Doctrine and want to copy an entity who contains a `Collection` that you want to be reset, you can use the
279
`DoctrineEmptyCollectionFilter`
280
 
281
```php
282
use DeepCopy\DeepCopy;
283
use DeepCopy\Filter\Doctrine\DoctrineEmptyCollectionFilter;
284
use DeepCopy\Matcher\PropertyMatcher;
285
 
286
$copier = new DeepCopy();
287
$copier->addFilter(new DoctrineEmptyCollectionFilter(), new PropertyMatcher('MyClass', 'myProperty'));
288
 
289
$copy = $copier->copy($object);
290
 
291
// $copy->myProperty will return an empty collection
292
```
293
 
294
 
295
#### `DoctrineProxyFilter` (filter)
296
 
297
If you use Doctrine and use cloning on lazy loaded entities, you might encounter errors mentioning missing fields on a
298
Doctrine proxy class (...\\\_\_CG\_\_\Proxy).
299
You can use the `DoctrineProxyFilter` to load the actual entity behind the Doctrine proxy class.
300
**Make sure, though, to put this as one of your very first filters in the filter chain so that the entity is loaded
301
before other filters are applied!**
991 lars 302
We recommend to decorate the `DoctrineProxyFilter` with the `ChainableFilter` to allow applying other filters to the
303
cloned lazy loaded entities.
148 lars 304
 
305
```php
306
use DeepCopy\DeepCopy;
307
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
308
use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher;
309
 
310
$copier = new DeepCopy();
991 lars 311
$copier->addFilter(new ChainableFilter(new DoctrineProxyFilter()), new DoctrineProxyMatcher());
148 lars 312
 
313
$copy = $copier->copy($object);
314
 
315
// $copy should now contain a clone of all entities, including those that were not yet fully loaded.
316
```
317
 
318
 
319
#### `ReplaceFilter` (type filter)
320
 
321
1. If you want to replace the value of a property:
322
 
323
```php
324
use DeepCopy\DeepCopy;
325
use DeepCopy\Filter\ReplaceFilter;
326
use DeepCopy\Matcher\PropertyMatcher;
327
 
328
$copier = new DeepCopy();
329
$callback = function ($currentValue) {
330
  return $currentValue . ' (copy)'
331
};
332
$copier->addFilter(new ReplaceFilter($callback), new PropertyMatcher('MyClass', 'title'));
333
 
334
$copy = $copier->copy($object);
335
 
336
// $copy->title will contain the data returned by the callback, e.g. 'The title (copy)'
337
```
338
 
339
2. If you want to replace whole element:
340
 
341
```php
342
use DeepCopy\DeepCopy;
343
use DeepCopy\TypeFilter\ReplaceFilter;
344
use DeepCopy\TypeMatcher\TypeMatcher;
345
 
346
$copier = new DeepCopy();
347
$callback = function (MyClass $myClass) {
348
  return get_class($myClass);
349
};
350
$copier->addTypeFilter(new ReplaceFilter($callback), new TypeMatcher('MyClass'));
351
 
352
$copy = $copier->copy([new MyClass, 'some string', new MyClass]);
353
 
354
// $copy will contain ['MyClass', 'some string', 'MyClass']
355
```
356
 
357
 
358
The `$callback` parameter of the `ReplaceFilter` constructor accepts any PHP callable.
359
 
360
 
361
#### `ShallowCopyFilter` (type filter)
362
 
363
Stop *DeepCopy* from recursively copying element, using standard `clone` instead:
364
 
365
```php
366
use DeepCopy\DeepCopy;
367
use DeepCopy\TypeFilter\ShallowCopyFilter;
368
use DeepCopy\TypeMatcher\TypeMatcher;
369
use Mockery as m;
370
 
371
$this->deepCopy = new DeepCopy();
372
$this->deepCopy->addTypeFilter(
373
	new ShallowCopyFilter,
374
	new TypeMatcher(m\MockInterface::class)
375
);
376
 
377
$myServiceWithMocks = new MyService(m::mock(MyDependency1::class), m::mock(MyDependency2::class));
378
// All mocks will be just cloned, not deep copied
379
```
380
 
381
 
382
## Edge cases
383
 
384
The following structures cannot be deep-copied with PHP Reflection. As a result they are shallow cloned and filters are
385
not applied. There is two ways for you to handle them:
386
 
387
- Implement your own `__clone()` method
388
- Use a filter with a type matcher
389
 
390
 
391
## Contributing
392
 
393
DeepCopy is distributed under the MIT license.
394
 
395
 
396
### Tests
397
 
398
Running the tests is simple:
399
 
400
```php
401
vendor/bin/phpunit
402
```
403
 
404
### Support
405
 
406
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).