Parcourir la source

Introduce cloning of returned values from Config.

Maciej Gołaszewski il y a 7 ans
Parent
commit
57571df099

+ 2 - 2
packages/ckeditor5-utils/src/config.js

@@ -7,7 +7,7 @@
  * @module utils/config
  */
 
-import { isPlainObject } from 'lodash-es';
+import { isPlainObject, cloneDeep } from 'lodash-es';
 
 /**
  * Handles a configuration dictionary.
@@ -198,7 +198,7 @@ export default class Config {
 		}
 
 		// Always returns undefined for non existing configuration
-		return source ? source[ name ] : undefined;
+		return source ? cloneDeep( source[ name ] ) : undefined;
 	}
 
 	/**

+ 36 - 1
packages/ckeditor5-utils/tests/config.js

@@ -19,7 +19,14 @@ describe( 'Config', () => {
 					path: 'xyz'
 				}
 			},
-			toolbar: 'top'
+			toolbar: 'top',
+			options: {
+				foo: [
+					{ bar: 'b' },
+					{ bar: 'a' },
+					{ bar: 'z' }
+				]
+			}
 		} );
 	} );
 
@@ -371,5 +378,33 @@ describe( 'Config', () => {
 				config.resize.maxHeight;
 			} ).to.throw();
 		} );
+
+		it( 'should not be possible to alter config object by altering returned value', () => {
+			expect( config.get( 'resize.icon.path' ) ).to.equal( 'xyz' );
+
+			const icon = config.get( 'resize.icon' );
+			icon.path = 'foo/bar';
+
+			expect( config.get( 'resize.icon.path' ) ).to.equal( 'xyz' );
+
+			const resize = config.get( 'resize' );
+			resize.icon.path = 'foo/baz';
+
+			expect( config.get( 'resize.icon.path' ) ).to.equal( 'xyz' );
+		} );
+
+		it( 'should not be possible to alter array in config by altering returned value', () => {
+			expect( config.get( 'options.foo' ) ).to.deep.equal( [ { bar: 'b' }, { bar: 'a' }, { bar: 'z' } ] );
+
+			const fooOptions = config.get( 'options.foo' );
+			fooOptions.pop();
+
+			expect( config.get( 'options.foo' ) ).to.deep.equal( [ { bar: 'b' }, { bar: 'a' }, { bar: 'z' } ] );
+
+			const options = config.get( 'options' );
+			options.foo.pop();
+
+			expect( config.get( 'options.foo' ) ).to.deep.equal( [ { bar: 'b' }, { bar: 'a' }, { bar: 'z' } ] );
+		} );
 	} );
 } );