Created
July 13, 2022 20:50
-
-
Save snellingio/b712b5dd20b330adaea2cb75b948dd7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AssociativeArray } from '../php/types' | |
import array_key_exists from '../php/array_key_exists' | |
import is_callable from '../php/is_callable' | |
import is_string from '../php/is_string' | |
class Fluent { | |
private _attributes: AssociativeArray = {} | |
constructor(attributes: AssociativeArray = {}) { | |
Object.assign(this._attributes, attributes) | |
return new Proxy(this, { | |
// @ts-ignore | |
get(target: this, p: string | symbol, receiver: any): any { | |
if (is_string(p)) { | |
if (array_key_exists(p, target._attributes)) { | |
return target._attributes[p] | |
} | |
} | |
if (!target[p]) { | |
return function (value: any = null) { | |
if (value === null) { | |
value = true | |
} | |
target._attributes[p] = value | |
// @ts-ignore | |
return this | |
} | |
} | |
return target[p] | |
}, | |
// @ts-ignore | |
set(target: this, p: string | symbol, value: any, receiver: any): this { | |
console.log('set', target) | |
target._attributes[p] = value | |
return target | |
}, | |
}) | |
} | |
get(key: string | number, defaultValue: any = null) { | |
if (array_key_exists(key, this._attributes)) { | |
return this._attributes[key] | |
} | |
if (is_callable(defaultValue)) { | |
return defaultValue.call() | |
} | |
return defaultValue | |
} | |
getAttributes() { | |
return this._attributes | |
} | |
} | |
export default Fluent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment